Abubakkar
Abubakkar

Reputation: 15644

UnknownHostException is not recognized in catch block

One of the method in my code throws UnknownHostException exception

I first had a catch block like this:

catch (Exception e) {
  // TODO Auto-generated catch block
  System.out.println("Custom Message "+e.getMessage());
  if(e instanceof java.net.UnknownHostException){
      System.out.println("Unknown Host Ex");
  }else{
      System.out.println("OTHER ERROR");
  }
}

I am facing a problem where that if condition never evaluates to true and hence I am not able to output that there is some host error.

You can see I have a sysout just before that which prints this :

Custom Message ; nested exception is: 
    java.net.UnknownHostException: abc.xyz

After that I wrote a seperate catch block to handle UnknownHostException but still is it not getting catched.

Upvotes: 7

Views: 14039

Answers (2)

Alex
Alex

Reputation: 25613

UnknownHostException is nested inside another Exception so it may not be an instance of it but it just contains it. You may eventually check e.getCause()

Upvotes: 2

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340708

Well, apparently your UnknownHostException in wrapped in some other exception. In other words some code above catches UnknownHostException and throws:

throw new SomeOtherException("Custom Message", unknownHostEx);

Print e.getClass() to see what kind of exception is wrapping it. You can also try:

if(e.getCause() != null && e.getCause() instanceof UnknownHostException)

but it's ugly.

BTW you should avoid using instanceof and let catch figure out the exception itself (but it won't help in your case):

catch (java.net.UnknownHostException e) {
      System.out.println("Unknown Host Ex");
}
catch (Exception e) {
      System.out.println("OTHER ERROR");
}

Upvotes: 13

Related Questions