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?
也许您可以尝试将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.
| 归档时间: |
|
| 查看次数: |
38679 次 |
| 最近记录: |