java instanceof 是否适用于子类异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4154080/
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-30 05:04:11  来源:igfitidea点击:

does instanceof work for subclassed exceptions?

javaexception-handling

提问by Jimmy

java.net.ConnectExceptionextends java.net.SocketException

java.net.ConnectException延伸 java.net.SocketException

If I do the following, will it cater for both exceptions? ie if I catch a "parent" exception using instanceof, does that include any subclassed exceptions?

如果我执行以下操作,它会同时满足这两种例外情况吗?即,如果我使用 捕获“父”异常instanceof,是否包括任何子类异常?

catch (Exception e)
{
   if (e instanceof java.net.SocketException)
   {
      System.out.println("You've caught a SocketException, OR a ConnectException");
   }
}

(and for the record, yes I know catching plain Exceptions is bad, just using it for this example ;) )

(并且为了记录,是的,我知道捕获普通异常是不好的,只是在这个例子中使用它;))

回答by Bozho

Exceptions are regular classes, so instanceofworks fine for them.

例外是常规类,因此instanceof对它们来说效果很好。

But you don't need such a thing. The following achieves the same result:

但是你不需要这样的东西。以下实现了相同的结果:

try {
    throw new ConnectException();
} catch (SocketException e) {
    System.out.println("You've caught a SocketException, OR a ConnectException");
}

回答by Nico Huysamen

Yes, it will cater for both. Because ConnectionException IS A SocketException, it also is an instance of it.

是的,它会兼顾两者。因为 ConnectionException 是一个 SocketException,所以它也是它的一个实例。

回答by Mot

Bozho already has given the right answer. I don't know your particular usecase, but you'd rather catch different exceptions:

博卓已经给出了正确的答案。我不知道您的特定用例,但您宁愿捕获不同的异常:

try {
  ...
}
catch (SocketException ex) {
  System.out.println("You've caught a SocketException, OR a ConnectException");
}
catch (Exception ex) {
  ...
}

回答by mexekanez

I know that it's now a good way but if you want to do custom action in a many places in code you can do something like this: public class ImageIOExecption extends Exception {

我知道现在这是一个好方法,但是如果您想在代码中的许多地方进行自定义操作,您可以执行以下操作: public class ImageIOExecption extends Exception {

Exception ex;

public ImageIOExecption(Exception ex) {
    this.ex = ex;
    doCatch();
 }

private void doCatch() {
    System.err.println(ex.getClass());

    if (ex instanceof java.net.SocketTimeoutException) {
        System.out.println("You've caught a SocketTimeoutException, OR a ConnectException");
    }

    if (ex instanceof java.net.SocketException) {
        System.out.println("You've caught a SocketException, OR a ConnectException");
    }


}
}

 public BufferedImage getBufferedImage() {
        try {
            BufferedImage srcImage = ImageIO.read(is);
            is.close();
            return  srcImage;
        } catch (Exception ex) {
            new ImageIOExecption(ex);
        }
        return null;
    }

回答by brain

Yes, that is how instanceofworks. For exceptions it is more common to use something like this if you care about different exceptions. It works because the JVM will work down the list of catch statements in order and execute the first one that matches.

是的,这就是instanceof工作原理。对于异常,如果您关心不同的异常,则使用类似的方法更为常见。它起作用是因为 JVM 将按顺序处理 catch 语句列表并执行第一个匹配的语句。

catch(ConnectException e)
{
    //got ConnectException  
}
catch(SocketException e)
{
    /got a SocketException
}
catch(Exception e)
{
   //got some other exception
}

Or below if you dont care about the difference between Connection and Socket Exception

或者下面如果你不关心连接和套接字异常之间的区别

catch(SocketException e)
{
   //got a SocketException or a subclass e.g. ConnectionException
}
catch(Exception e)
{
   //got another type of exception
}