UnknownHostException not recognized in catch block

One of my code's methods throws an UnknownHostException

I first had a catch 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 ran into a problem when this if condition if never evaluated as true, and therefore I cannot fulfill the conclusion that there is some kind of node error.

You can see that I have sysout just before typing this:

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

After that, I wrote a separate catch block to handle UnknownHostException , but still it doesn't get caught.

+4
source share
2 answers

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

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

Print e.getClass() to see which exception it wraps. You can also try:

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

but it is ugly.

By the way, you should avoid using instanceof and catch define the <exception> of the exception itself (but this will not help in your case):

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

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

+2
source

Source: https://habr.com/ru/post/1447895/


All Articles