Posts

Showing posts from November, 2021

Checked exceptions, type parameters, and higher-order functions

Image
One of the peculiar features of Java, in what's otherwise a rather mundane language, is checked exceptions. What do checked exceptions do? The short explanation is: They make information about what exceptions a method may throw part of its signature, and force you to actually handle all exceptions that may arise. A better way to explain it is through a few small examples... Checked exceptions Let's try to implement a trivial method that may throw an exception: class QuickMaths { class ZeroDivisionException extends Exception { } // Divide x by y, making sure y isn't zero. Double divide(Number x, Number y) { if (y == 0) { throw new ZeroDivisionException(); } else { return x * 1.0 / y; } } } The method divide is going to cause a compiler error, because it may throw an exception but we haven't encoded this information in its signature. (Sure, the compiler could infer this, but it doesn'