声明方法以引发异常和该异常的子类 [英] Declare method to throw an exception and subclass of this exception

查看:72
本文介绍了声明方法以引发异常和该异常的子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

声明一个引发异常
和该异常的子类
的方法是否有意义,例如 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆