Tag: API design

Fellow Atlassian Charles Miller recently wrote an amusing post about methods and constructors in Java that declare a checked exception, but can be called in a way that is required by the specification not to fail. A common example involves string encodings:

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.

The unnecessary exception-handling code is ugly, and obscures the actual intent of the method in which it appears. Charles jokingly proposes adding a “yoda” statement to Java to tell the JVM, “do, or do not; there is no try.”