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?
In addition to wanting to do something with the exception before exiting - like logging, the other time you would do something like that is if you want to wrap it as a different exception, like:
I would only catch/rethrow an exception (instead of just throwing it) if I wanted to do something else in the catch block - for example, write a logging statement before rethrowing.
You are right. Second version is better. Moreover the first version does not make any sense. It does the same except the stack trace of the exception will be "wrong".
There are the following reasons to "re-throw" exceptions:
example:
Both versions will output the same stacktrace
without try/catch
will output
with try/catch/throw same exception
will output exactly the same as before
try/catch/throw wrapping exception
An advisable approach is to throw your own exceptions. wrap the exception you just caught into it if you want to provide details of the root cause (might be wanted or not wanted)
You can clearly see the top-level issue (my process did not complete), and the root cause that led to it (java.pdf file not found)
The question is why you think you need to rethrow the exception. Did Eclipse suggest surrounding with
try-catch
? In practice we rarely rethrow the same exception, but very often catch one and throw another that wraps the first one, especially if the wrapper exception is unchecked. This happens whenever you have calls declaring checked exceptions, but the method you write those calls in doesn't declare those exceptions:In the example given, re-throwing the
Exception
serves no purpose.Doing this can be useful if the method that catches and then re-throws the exception needs to take some additional action upon seeing the
Exception
, and also desires that theException
is propagated to the caller, so that the caller can see theException
and also take some action.