首页 > 解决方案 > 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?

标签: javaexception

解决方案


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).


推荐阅读