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.