JSR-666 Extension: Unthrowable Exceptions

by Charles Miller on March 7, 2008

The following is a not uncommon occurrence in Java:

try {
    s = new String(byteArray, "UTF-8");
} catch (UnsupportedEncodingException e) {
    throw new Error("UTF-8 is missing??");

This code is the result of two conflicting factors. On one hand, since the constructor in question takes an arbitrary character encoding, the case of the encoding being unavailable must be taken into account. On the other hand, 90% of code that calls this constructor will be explicitly invoking a character set that is required to be provided with the Java Runtime Environment, and its absence would be an error serious enough to justify terminating the VM entirely.

Similar structures can be found in code that performs cryptography or reflection.

As such, the JSR-666 expert group recommends the introduction of the yoda code-word to the Java language. This keyword commands that the virtual machine "Do, or do not", where there is no corresponding try.

While in yoda-mediated code, any matching exception will automatically be caught and rethrown as an AssertionError (even if assertions are otherwise disabled):

yoda (UnsupportedEncodingException) {
    String s = new String(byteArray, "UTF-8");

Or at the method level:

public void myMethod() 
    yodas UnsupportedEncodingException { ... }

Warning: the yoda keyword should only be used in places where the presence of an exception would indicate the Java Runtime Environment is misconfigured or broken. Misusing the keyword may cause a great disturbance in the Virtual Machine, as if millions of voices suddenly cried out in terror and were suddenly silenced

This proposal acts as a companion to the previous JSR-666 exception handling proposal.

Previously: Java Developers...

Next: An iPhone SDK Halo Effect?