Question

With Java 1.7, the following code

try
{
  sck = SocketChannel.open();
  sck.configureBlocking(false);

  sck.connect(new java.net.InetSocketAddress(**<bad remote ip address>**, remote_port));
  sel = Selector.open();

  ...
}
catch (IOException e)
{
  return false;
}

doesn't seem to catch the exception if the remote address is a bad DNS (for instance). What did I miss?

Était-ce utile?

La solution

The UnresolvedAddressException is not a subclass of IOException, which is why you won't catch it if it's thrown.

UnresolvedAddressException is a subclass of IllegalArgumentException, as shown here, so try catching:

  • UnresolvedAddressException itself, as it's always better practice to catch the most specific exception type first
  • Exception if you don't really care about the exception you catch, as you can always halt the program or work around that

Edit: You probably missed that exception because the compiler did not force you to catch it. That is because UnresolvedAddressException is derived from RuntimeException, the type of exceptions which smack you in the head during execution. The exceptions not derived from RuntimeException, such as IOException, have to be caught, which is why your compiler probably told you to wrap your code into a try-catch block in the first place.

Autres conseils

UnresolvedAddressException is not a child of IOException. UnresolvedAddressException extends RuntimeException. You can try to add catch closure with RuntimeException.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top