繁体   English   中英

您如何检查异常的类型以及嵌套异常的类型?

[英]How do you check both the exception's type as well as they type of the nested exception?

假设我捕获了一个AppException类型的异常,但我只想对该异常执行某些操作,如果它有一个StreamException类型的嵌套异常。

if (e instanceof AppException)
{
    // only handle exception if it contains a
    // nested exception of type 'StreamException'

如何检查嵌套的StreamException

做: if (e instanceof AppException and e.getCause() instanceof StreamException)

也许不是检查原因,您可以尝试将 AppException 子类化以用于特定目的。

例如。

class StreamException extends AppException {}

try {
    throw new StreamException();
} catch (StreamException e) {
   // treat specifically
} catch (AppException e) {
   // treat generically
   // This will not catch StreamException as it has already been handled 
   // by the previous catch statement.
}

你也可以在java中的其他地方找到这种模式。 一个是示例IOException 它是许多不同类型 IOException 的超类,包括但不限于 EOFException、FileNotFoundException 和 UnknownHostException。

if (e instanceof AppException) {
    boolean causedByStreamException = false;
    Exception currExp = e;
    while (currExp.getCause() != null){
        currExp = currExp.getCause();
        if (currExp instanceof StreamException){
            causedByStreamException = true;
            break;
        }
    }
    if (causedByStreamException){
       // Write your code here
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM