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

Tim*_*thy 19 java exception instanceof

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

if (e instanceof AppException)
{
    // only handle exception if it contains a
    // nested exception of type 'StreamException'
Run Code Online (Sandbox Code Playgroud)

如何检查嵌套StreamException

Mar*_*elo 21

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


Dun*_*nes 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.
}
Run Code Online (Sandbox Code Playgroud)

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