Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:
public class Foo {
public void bar() throws AnException {
// do something (1)
try {
// do something (2) -- able to throw AnException
} catch (AnException ex) {
throw ex;
}
// do something (3)
}
}
Contrast this to:
public class Foo {
public void bar() throws AnException {
// do something (1)
// do something (2) -- able to throw AnException
// do something (3)
}
}
Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?
P.S. this question is very different from this question.
EDIT: The catch
block in the former doesn't do anything else other than rethrowing the caught exception.
Generally, you catch many exceptions, generalize them into one and throw it.. So that all similar exceptions can be handled in the same way..
If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.
The purpose of the rethrow operation is to get the attention of the outside world that an exception has occurred and at the same time perform any contingency logic (such as logging) in the catch block.
The throw keyword in Java is used to explicitly throw either a custom-made exception or in-built exception. But sometimes in the catch block, we need to throw the same exception again. This leads to re-throwing an exception.
This is a violation of a basic rule:
The code should catch only the exceptions that it knows how to handle.
Oracle's guidelines suggests that each time you throw an exception, you should supply something useful for the code that catches your exception (see page 3 of Effective Java Exceptions). Catching an exception simply to re-throw it serves no practical purpose, because there is no additional information added to it for the code above it in the invocation chain, and no information extracted by the method itself.
It makes no sense for sure assuming code you provided. Rethrowing exceptions makes sense when you want to handle this exception somehow (e.g. log it) but want it to be handled further in a stack trace.
Regarding commercial code, maybe the reason you saw it was that there was some handling logic initially that was removed but exceptions rethrowing wasn't removed. I saw such situations several times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With