Tags

Unchecking exceptions

July 15th, 2007

First of all I am not for removing checked exceptions from the language. Quite often I am annoyed by them, but that doesn’t mean that we should pour the baby with the bath.

The problem

The classic is Method.invoke(). This method declares five checked exceptions, but when you are using checked exceptions seriously you’ll get situations like that all over where you can’t deal with the exception and it gets just rethrown as

throw new MyRuntimeException(e);

If all catch blocks look the same you should rethink the exception handling strategy in your, but if not - read on.

There are good reasons why not declaring all possible exceptions in all using methods, the most obvious is that this ripples through your code (I assume you IDE can automatically add/remove the necessary throws while editing) and in a large project this will create constantly problems with merging versions. More severe is that the exceptions leak implementation details, thus the standard technique is wrapping exceptions into types declared by your API.

Catch annotations

What about injecting the exception handling where you need it? (Remark:The annotations might not be the right way of doing it, but for illustrating the idea it is good enough)

@catch(ex=CheckedException.class)
void myMethod() {

do();//throws CheckedException

}

The annotation has the effect of wrapping each statement that declares CheckedException into

try {

do();

} catch(CheckedException ce) {

throw new RuntimeException(ce);

}

This covers perhaps 60% of the bogus catches in an environment that uses checked exceptions heavily, another annotation

@cast(ex=CheckedException.class, to=MyRuntimeException.class)

covers most of the remaining cases by assigning a target exception to the type to be caught. if we allow to have multiple annotations for a method.

@cast(ex=SQLException.class, to=MyRuntimeException.class) //throw MyRuntimes for all SQL ex.
@catch(Exception.class) // throw the rest as RuntimeException
void myMethod()

Further ideas

  • The annotation should be allowed also at class level for having a better structured exception strategy.
  • Class-level annotations are (overridable) inherited to the methods
  • The target exception needs not to be a RuntimeException