java 在 catch 块中无法识别 UnknownHostException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13525946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
UnknownHostException is not recognized in catch block
提问by Abubakkar
One of the method in my code throws UnknownHostException
exception
我的代码中的方法之一抛出UnknownHostException
异常
I first had a catch
block like this:
我首先有一个catch
这样的块:
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.
我面临一个问题,该if
条件永远不会评估为真,因此我无法输出存在某些主机错误的信息。
You can see I have a sysout
just before that which prints this :
你可以看到我sysout
在打印这个之前有一个:
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.
之后我写了一个单独的 catch 块来处理,UnknownHostException
但它仍然没有被捕获。
回答by Tomasz Nurkiewicz
Well, apparently your UnknownHostException
in wrapped in some other exception. In other words some code above catches UnknownHostException
and throws:
好吧,显然您UnknownHostException
的内容包含在其他一些异常中。换句话说,上面的一些代码捕获UnknownHostException
并抛出:
throw new SomeOtherException("Custom Message", unknownHostEx);
Print e.getClass()
to see what kind of exception is wrapping it. You can also try:
打印e.getClass()
以查看包装它的异常类型。你也可以试试:
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):
顺便说一句,您应该避免使用instanceof
并catch
自行找出异常(但它对您的情况无济于事):
catch (java.net.UnknownHostException e) {
System.out.println("Unknown Host Ex");
}
catch (Exception e) {
System.out.println("OTHER ERROR");
}
回答by Alex
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()
UnknownHostException
嵌套在另一个内部,Exception
因此它可能不是它的实例,但它只是包含它。你最终可能会检查e.getCause()