Finding good generic practices on exception handling is not so easy, it depends too much on the concrete context. It's much easier to think about what are bad practices instead. Here are a few things I don't like to see in the source code in general.
Swallowing the exception
Problems remain undetected.
try {
doSomething();
} catch(MyException e) {
// do nothing
}
Fake return value
Only logging the exception may be fine in some scenarios, but the made-up return value is asking for trouble. Without logging it's even worse.
try {
return doSomething();
} catch (MyException e) {
log.error(e.getMessage(), e);
return null;
}
Lossy wrapping
Stacktrace of the original exception gets lost.
try {
doSomething();
} catch(MyException e){
throw new MyOtherException(e.getMessage());
}
Checked base exception
Specifying the base exception adds no real value.
public void doSomething() throws Exception {
}
Throwing the kitchen sink
If they're handled the same way, definition of all those checked exceptions becomes pointless in the method signature.
private void doSomething() throws MyException, AnotherException, YetAnotherException {
}
public void foo() {
try {
doSomething();
} catch(MyBaseException e) {
// handle the exception
}
}
Catching base exception
The wrong exception may be handled.
private void doSomething() throws MyException {
}
public void foo() {
try {
doSomething();
} catch(Exception e) {
// handle the exception
}
}
Throwing exception in finally
This code is fine, as long as cleanUp() can never throw an exception. If it does, the details of any exception thrown in doSomething() will be lost.
try {
doSomething();
} finally {
cleanUp();
}
Relying on cause
Relies too much on the composition of the exception. That might change and the code won't work as expected.
catch (MyException e) {
if (e.getCause() instanceof MySubException) {
// ..
}
Log and throw
Only partial stack trace gets logged, the exception can potentially be logged multiple times. In some scenarios it can be justified (loss of exception details at remote invocations).
catch(MyException e) {
log.error(e.getMessage(), e);
throw new MyOtherException(e);
}
No comments:
Post a Comment