Rethrow exception in java

2020-02-01 01:45发布

I have a very simple question about re-throwing exception in Java.

Here is the code snippet:

public static void main(String[] args) throws FileNotFoundException {
    try {
        FileReader reader = new FileReader("java.pdf");
    } catch (FileNotFoundException ex) {
        throw ex;
    }
}

public static void main(String[] args) throws FileNotFoundException {        
        FileReader reader = new FileReader("java.pdf");        
}

Why do we need to re-throw ex in the first version while the second version looks more elegant? What might be the benefits and which version is preferred over the other?

7条回答
Root(大扎)
2楼-- · 2020-02-01 02:25

The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception.

If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace.

If the method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.

One can do this by including a throws clause in method's declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared int the throws clause. If they are not, a compile-time error will result.

查看更多
登录 后发表回答