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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:05:46  来源:igfitidea点击:

UnknownHostException is not recognized in catch block

javaexceptionexception-handling

提问by Abubakkar

One of the method in my code throws UnknownHostExceptionexception

我的代码中的方法之一抛出UnknownHostException异常

I first had a catchblock 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 ifcondition 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 sysoutjust 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 UnknownHostExceptionbut still is it not getting catched.

之后我写了一个单独的 catch 块来处理,UnknownHostException但它仍然没有被捕获。

回答by Tomasz Nurkiewicz

Well, apparently your UnknownHostExceptionin wrapped in some other exception. In other words some code above catches UnknownHostExceptionand 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 instanceofand let catchfigure out the exception itself (but it won't help in your case):

顺便说一句,您应该避免使用instanceofcatch自行找出异常(但它对您的情况无济于事):

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

回答by Alex

UnknownHostExceptionis nested inside another Exceptionso it may not be an instance of it but it just contains it. You may eventually check e.getCause()

UnknownHostException嵌套在另一个内部,Exception因此它可能不是它的实例,但它只是包含它。你最终可能会检查e.getCause()