实例是为子类异常工作吗? [英] does instanceof work for subclassed exceptions?
本文介绍了实例是为子类异常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
java.net.ConnectException
extends java.net.SocketException
java.net.ConnectException
extends java.net.SocketException
如果我执行以下操作,它是否适用于这两个例外?即如果我使用 instanceof
捕获父异常,那么是否包含任何子类异常?
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?
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 ;) )
推荐答案
异常是常规类,所以 instanceof
可以正常工作。
Exceptions are regular classes, so instanceof
works fine for them.
但是你不需要这样的东西。以下实现相同的结果:
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");
}
这篇关于实例是为子类异常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文