声明方法以引发异常和该异常的子类 [英] Declare method to throw an exception and subclass of this exception
问题描述
声明一个引发异常
和该异常的子类
的方法是否有意义,例如 IOException 和 FileNotFoundException ?
我猜想它是用来通过调用方方法不同地处理两个异常的。
但是,如果方法仅抛出仅最通用的类型,即 IOException ,则可以处理这两种异常吗?
I guess that it is used in order to handle both exceptions by a caller method differently. However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
推荐答案
但是,如果该方法仅抛出最通用的异常(即IOException),是否可以处理这两个异常?
However, is it possible to handle both exceptions if the method throws only the most generic i.e IOException?
绝对。您仍然可以分别捕获它们:
Absolutely. You can still catch them separately:
try {
methodThrowingIOException();
} catch (FileNotFoundException e) {
doSomething();
} catch (IOException e) {
doSomethingElse();
}
因此,呼叫者可以做什么如果方法同时声明了两者,则执行-这是多余的。但是,它可以强调您可能要考虑的异常。在Javadoc中,这可能比throws声明更好。
So it makes no difference to what the caller can do if the method declares both - it's redundant. However, it can emphasize exceptions that you might want to consider. This could be done better in Javadoc than just the throws declaration.
这篇关于声明方法以引发异常和该异常的子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!