Tuesday, November 17, 2015

Java Exception Propagation and Handling


Today I had to design some interfaces for an infrastructure component that we are developing and one of the questions in my mind was about what would be the correct exception handling mechanisms for the implementations of this interface.  I found a very nice and informative article here by Brian Goetz an authoritative expert source on Java   :

Java theory and practice: The exceptions debate

For those who have worked for some time with Java,  the terms checked exceptions  and unchecked exceptions would immediately spring to your mind.  To state in a brief one-liner :

Checked Exceptions derive from java.lang.Exception whereas Unchecked Exceptions derive from java.lang. RuntimeException.

An interface declaration has to explicitly declare the type of checked exceptions that could be thrown from it's methods. This means that the client invoking these methods should handle them explicitly using the try-catch-finally technique or must re-throw  them so that they are handled up the call stack. For example, many methods within the JDBC SPI throw SQLException. This mandates callers using the SPI to handle this exception or re-throw it.

 Unchecked exceptions on the other hand need not be explicitly declared within the interface definition. For example if the implementation of an interface does not support a method then it throws an UnsupportedOperationException which is a RuntimeException. For an even more concrete example  see the implementation of the Collections.unmodiableList. More specifically see how java.util.Collections.UnmodifiableList has been implemented.

So in order to design interfaces correctly - please re-read exception handling, think through the functionality and yes definitely read the link posted above.

Happy Coding!!