Wednesday, September 05, 2007

Intergalactic Gotos and the WrappingWronglyCheckedExceptionException Proposal

There is debate about if checked exceptions have their right or not. I think they might have, but more often than not, we use exceptions like intergalactic gotos instead. Many exceptions in the Java APIs that are checked, should have been unchecked in my opinion. The other day, I wrote this code:

String s = ....
return s.getBytes("UTF-8");

And the compiler told me, that getBytes(String) throws the checked exception UnsupportedEncodingException, which I am then forced to catch. So, I end up with:

try {
String s = ....
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// what the f*** to do with that?
}

The JRE documentation of the java.lang package documents, that UTF-8 is one of the encodings, that all implementations are required to support. So, if I use this method correctly according to its api, and only ask for encodings required to be supported, then it will be a runtime error, if the encoding is not supported.

So, what about adding this exception to commons-lang:

public class WrappingWronglyCheckedExceptionException extends RuntimeException {
...
}

Then, I would know what to fill into my catch-block in such cases.

3 comments:

ccondit said...

My usual handling of this case:

try
{
String s = ....
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e)
{
throw new RuntimeException("Your JRE is hosed, dude!", e);
}

Better yet, that same code in a StringUtils.getUtf8Bytes(String s) method which doesn't throw a checked exception.

Ricky Clarkson said...

Clearly in this case it would be better if getBytes took a CharacterEncoding, and there was some way of grabbing the UTF-8 encoding, e.g., CharacterEncodings.UTF8. Then there would be no need for getBytes to throw an exception.

In general, the problem with checked exceptions is that whether you want to be forced to handle them depends on the call site.

Per Olesen said...

"..In general, the problem with checked exceptions is that whether you want to be forced to handle them depends on the call site...

Yes, I think you are spot on there. But I think there is more into it, than that. I think most checked exceptions could be handled with a specific return value, instead of throwing an exception to let the caller "goto" some handling code.