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

时间:2011-06-25 17:08:56

标签: java exception instanceof

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

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

如何检查嵌套StreamException

3 个答案:

答案 0 :(得分:21)

执行:if (e instanceof AppException and e.getCause() instanceof StreamException)

答案 1 :(得分:5)

也许不是检查原因,而是可以尝试为特定目的继承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。

答案 2 :(得分:1)

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
    }
}