Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Abubakkar Avatar asked Nov 23 '12 09:11

Abubakkar


2 Answers

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

like image 42
Alex Avatar answered Nov 16 '22 03:11

Alex


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");
}
like image 60
Tomasz Nurkiewicz Avatar answered Nov 16 '22 03:11

Tomasz Nurkiewicz