What do you do about checked exceptions that you know will never be thrown? One possibility is to just use an empty catch block but there is a better way.
The empty catch block technique would be something like the code below with a little comment to indicate that the exception is being ignored for a good reason.
try {
methodCall(param);
} catch (ExceptionThatIsNeverThrown e) {
// ignore as this will never happen
}
The nicer alternative is to create a subclass of java.lang.RuntimeException, perhaps called UnexpectedException, that can be used to wrap the exception that is caught and rethrow the UnexpectedException instance. A RuntimeException subclass must be used as your code may be in a method to which you can't add any more checked exceptions (usually because the method it overrides has a limited set that it throws and you can not add to that set.)
try {
methodCall(param);
} catch (ExceptionThatIsNeverThrown e) {
throw new UnexpectedException(e);
}
This way if the exception that will never occurs does occur at least you find out about it instead of having the program fail later for some other reason that is very difficult to trace back to the root cause.
Posted by Alex at February 01, 2002 09:07 PM