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?
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: