views:

35

answers:

2

Hi, 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());
+1  A: 

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();
}

viv
thanks viv.. is this normal for java coding? to handle exceptions that may occur before they actually do?
Grant
It is a good practice to do, but some where it wants that an exception of a particular kind have to be handled. Generally you should enclose all your code within try-catch, it's a nice practice.
viv
A: 

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.

ageektrapped