Disambiguating empty catch blocks
Bruce Chapman
brucechapman at paradise.net.nz
Tue Apr 13 08:18:27 UTC 2010
Empty catch blocks are ambiguous and can mean one of
- I want to ignore this exception - the code works correctly when the
catch block executes.
- I know that this exception will never actually occur in this
particular case - the catch block never executes.
- The catch block is incomplete - a bug.
To enable programmers to disambiguate these situations I propose adding
the following methods to Exception:
/**
This method does absolutely nothing. Calling it in a catch clause can be
used to explicitly indicate that the exception itself is being
deliberately ignored.
*/
public void ignore() {
}
and
/**
This method throws an AssertionError with this Exception as its
cause.
@throws an AssertionError
*/
public void impossible() {
AssertionError aPaddy =
new AssertionError("The impossible happened");
aPaddy.initCause(this);
throw aPaddy;
}
example:
byte[] rawMessage= ...;
String msg = null;
try {
msg = new String(rawMessage,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.impossible();
}
These two methods provide a means to make the programmer's intent
explicit for the first two meanings of an empty catch block and
satisfies tools (IDEs and static anaylsis) that the catch block isn't
just declaring an unused variable, thus enabling a more robust
interpretation of an empty catch block (or unused exception variable in
a catch block) as a problem to be rectified.
Some questions:
Is Exception the right home for this, or is there any value in hoisting
it into Throwable?
Any problems which I have overlooked?
Comments?
With a little encouragement (like someone offering to mentor this), I
will file an RFE for this, and start work on a changeset against
openJDK7 to implement it. Yes I realise that the javadoc needs a little
more development.
regards
Bruce Chapman
More information about the core-libs-dev
mailing list