Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does instanceof work for subclassed exceptions?

java.net.ConnectException extends java.net.SocketException

If I do the following, will it cater for both exceptions? ie if I catch a "parent" exception using instanceof, does that include any subclassed exceptions?

catch (Exception e)
{
   if (e instanceof java.net.SocketException)
   {
      System.out.println("You've caught a SocketException, OR a ConnectException");
   }
}

(and for the record, yes I know catching plain Exceptions is bad, just using it for this example ;) )

like image 597
Jimmy Avatar asked Dec 01 '22 04:12

Jimmy


2 Answers

Exceptions are regular classes, so instanceof works fine for them.

But you don't need such a thing. The following achieves the same result:

try {
    throw new ConnectException();
} catch (SocketException e) {
    System.out.println("You've caught a SocketException, OR a ConnectException");
}
like image 77
Bozho Avatar answered Dec 04 '22 22:12

Bozho


Yes, it will cater for both. Because ConnectionException IS A SocketException, it also is an instance of it.

like image 42
Nico Huysamen Avatar answered Dec 04 '22 22:12

Nico Huysamen