java - Why method that calls another one which throws RuntimeException needs return statement?
问题描述
Why unreachable statement is not identified by javac ?
public int directThrow(){
throw new RuntimeException();
//Compiles fine
}
public int indirectThrow(){
directThrow();
// Missing Return Statement error
}
解决方案
编译器根本不是为了深入分析您的代码而设计的。
对于directThrow
,编译器看着它说:“我看到你有一个 throw 语句,所以方法会在这里突然终止,那么就不需要 return 语句了!”
对于indirectThrow
,编译器看着它说:“我只看到一个方法调用。嘿,程序员!你需要一个 return 语句!”
编译器不会查看directThrow
实际执行的操作。我认为这是非常合理的,因为与增加编译时间的成本相比,分析你调用的每个方法所做的好处真的很小。想想编译器需要检查什么以确保directThrow
总是抛出异常。最重要的是,它是否被任何东西覆盖?你甚至可以检查吗?您甚至可以确保将来没有类将子类化您的类并覆盖该方法(给您的类并且directThrow
都是非final
)?
如果您想将一些复杂的异常抛出逻辑提取到方法中,则可以将其提取到返回的方法中Exception
:
private Exception someComplicatedLogicThatGivesAnException() { ... }
public void foo() {
if (...) {
throw someComplicatedLogicThatGivesAnException();
}
}
推荐阅读
- c - 将'float(float)'传递给不兼容类型'float'的参数
- python - 从 Lambda 函数访问私有 API
- java - 设置操作的优先级。计算器应用
- java - 按每行的平均值对二维数组进行排序
- javascript - 如何自定义 HTML DATE 输入.. 除了 jQuery datePicker 之外还有哪些选项?
- python-3.x - Julia 是否需要矢量化来加快计算速度?
- python - 如何使用 Python ping java 和基岩 Minecraft 服务器的信息
- arrays - 打字稿映射类型意外值签名
- python - python Opencv2 显示图像并同时调用其他函数
- node.js - 无法连接到mysql远程数据库