android – Unable to create a ServerSocket in eclipse (java) – Education Career Blog

i am very new to programming in java however have a lot of experience in .NET (c# & vb.net).

I am trying to create a new instance of a serversocket class in eclipse IDE and when i type the following code it is giving me an “Unhandled exception type IOException” and i havent even tried to run the code yet!!

I dont understand how my code is exceptioning before runtime or what i can do to fix it.

Can someone help me?

Offending code:

ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());

,

If it is giving “Unhandled exception type IOException”, in java file while editing, it means that you need to enclose this statement
in try-catch block

try{

ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
}catch(IOException ex){

e.printStackTrace();
}

,

This is a feature of the Java language called Checked Exceptions. Basically, there are Exceptions in code that you call that can be determined at compile time. The Java language designers thought it prudent to force you to handle them.

In this case the ServerSocket class constructor, in its method signature, declares that it throws an IOException.

There are two ways to make the compile error go away.

You can wrap the code in a try/catch.

try
{
    ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
} catch (IOException e)
{
    // handle exception
}

Or, you can pass responsibility on to the calling method. For example, suppose you called the ServerSocket constructor inside a method called createSocket(). You would declare your method like so

public ServerSocket createSocket() throws IOException
{
    ServerSocket server = new ServerSocket(1234, 5, InetAddress.getLocalHost());
    return server;
}

In this case, you’re just moving responsibility up the call chain, but sometimes that makes sense.

This is so common in the Java language, that Eclipse offers the two options above as Quick Fixes.

Leave a Comment