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?
The flow of execution stops immediately after the
throw
statement; any subsequent statements are not executed. The nearest enclosingtry
block is inspected to see if it has acatch
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 matchingcatch
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. Athrows
clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of typeError
orRuntimeException
, or any of their subclasses. All other exceptions that a method can throw must be declared int thethrows
clause. If they are not, a compile-time error will result.