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.
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()
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With