java - Unable to rethrow Exception
问题描述
I've created a class like below and am wondering why I am unable to simply catch and rethrow an exception:
public class TestClass implements Runnable {
@Override
public void run() {
try{
FileInputStream inStream = new FileInputStream("");
}catch(Exception e){
throw e;
}
}
}
Eclipse is showing a compilation error: "Unhandled exception type FileNotFoundException" and suggests the following fix, which for some reason compiles fine:
@Override
public void run() {
try{
FileInputStream istream = new FileInputStream("");
}catch(Exception e){
try {
throw e;
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
What is going on here?
解决方案
The constructor of FileInputStream
declares to throw a checked exception. According to the so-called catch or specify requirement, this means that methods that throw exceptions of this type must either catch it (which excludes rethrowing it), or declare it in their interface. Because your run
method does not declare it (and you can't because it overrides Runnable#run()
), you get the error.
If you catch the exception and swallow it with a print statement, then you meet the "catch" requirement and the error disappears. If you throw an exception that extends RuntimeException
instead, this is an unchecked exception and the catch or specify requirement does not apply.
Interestingly, the flow analysis done by the Eclipse compiler is slightly over-aggressive, which leads to the confusing and potentially incomplete error message
Unhandled exception type FileNotFoundException
An example where this type specificity would be incomplete is if you have the following code in your try
block:
Class.forName("foo");
FileInputStream inStream = new FileInputStream("");
Then you'll still get an error about FileInputStream
, even though forName
would also result in an unhandled checked exception of a different type (ClassNotFoundException
).
推荐阅读
- python - 如何禁用币安现货 API PRICE_FILTER?
- twitter-bootstrap - 如何在照片下方显示 2 个按钮?
- php - 是否可以检查 wp_enqueu_scripts 中呈现的页面内容?
- java - 与自定义 jTable 的单元格交互
- javascript - 使用 Javascript 中的函数从 API 调用返回 JSON 对象
- publish-subscribe - 建立数据订阅者。如何通过 IP 循环希望
- keycloak - 如何自定义 Keycloak 用户帐户?
- reactjs - 如何在 React 中创建多个布局?
- javascript - 使用 Express JS 的基本身份验证
- react-native - 如何在打开另一个下拉框视图时关闭?[反应 - 本机]