java - 为什么不能处理这个异常?
问题描述
假设我有这个例外:
class NoMoreCarrotsException extends Exception {}
这是一个已检查的异常,因此必须对其进行处理或声明。
假设我有这个方法:
private static void eatCarrot(){}
public void fails(){
try{
eatCarrot();
}catch(NoMoreCarrotsException e){}
}
和这个:
public void works() throws NoMoreCarrotsException {
eatCarrot();
}
为什么第二个有效但第一个无效?该eatCarrot
方法不会抛出异常,那么为什么我们可以声明/抛出它?
解决方案
您可以声明您的方法(works()
在这种情况下)throws
是一个异常,即使它没有抛出它。
原因是这将允许覆盖您的方法的子类抛出该异常(或该异常的任何子类)。
On the other hand, in a try-catch block, if you attempt to catch an exception that cannot be thrown by the try block, your catch block becomes dead code (i.e. code that can never be reached), and the compiler doesn't allow it.
推荐阅读
- c++ - 有人可以帮助我使用正则表达式吗?
- java - 从原点到点的路径数
- java - 为什么递归 MergeSort 比迭代 MergeSort 快?
- scala - Apache Flink Scala 流式处理
- r - 在ggplot中调整错误栏上方的文本位置
- django - 如何为我的应用程序实现内置信号?
- java - 如何解决:无法解析插件“org.springframework.ide.eclipse.ui”?
- excel - 在 Excel 中打开主文件时禁止打开参考文件
- html - React Native:如何使用 Webview 阅读来自 Wordpress 的视频帖子?
- sqlite - 如何在sqlite中过滤日期和时间之间的数据