Thursday, November 22, 2007

DiSaDvAnTaGeS of Using ~ Throws Exception ~ and ~ Throws Throwable ~

Using throws Throwable and throws Exception subverts the exception checking system. If you do this, callers are forced to catch Throwable or Exception, which may catch both unchecked and checked exceptions. This forces callers to use instanceof to see whether the exception is one that they can deal with.

Essentially, this defers the exception-checking mechanism from compile-time to runtime, which of course converts compile-time errors to runtime errors.

On a related note, there’s not much point in specifying unchecked exception types in a throws clause, for example throws RuntimeException or throws NullPointerException. This serves no purpose except documentation, and it’s better to use a @throws javadoc comment for this, as you can include more information in the javadoc comment.

1 comment:

Anonymous said...

Sorry to say that but I disaggree with this. Totally. First of all, NullPointerException is something you do not throw. There is no point. Either you let it "surface" by not placing risky code in a try/catch block. Or you catch it, and then throw a specific exception, caracterising the event of having an unexpected null value. For example MyItemNotFound exception, or MyInvalidPArameter exception. And in the surrounding try/catch, there is no need for type conversion. You simply indicate the type of error you want to catch:

try {...}
catch (MyFavoriteException e) {
// Do something with e
} catch (Exception e) {
//Do something with the unknown exception
}