Sunday, May 11, 2014

Checked vs Unchecked Exceptions


Yes, they are coupled with the compiler in that the compiler handles them differently from checked exception. This is covered to a certain extent at Unchecked Exceptions — The Controversy (The Java™ Tutorials > Essential Classes > Exceptions).


However this doesn't mean that you should never declare a method to throw a RuntimeException. Quoting from the article,


One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

In other words, a method can throw a RuntimeException, and specify in its signature that it does so, e.g.,


Java Code:



/**
* Example method that throws a RuntimeException
*
* @param obj Object with which to do something
* @throws NullPointerException if obj is null
*/
void doSomethingWithObj(Object obj) throws NullPointerException {
if (obj == null) {
throw new NullPointerException("obj is null");
}
// do something
}

You can, of course, not specify NullPointerException in the throws clause, but specifying it, especially with accompanying javadoc comments, clearly communicates to users of this method of the effect of using the method incorrectly. I find this especially useful with an IDE when I can mouse over the method name when calling it from another class, and see the javadoc comment in situ. You would've encountered cases where a null parameter value is a valid value. In the above case, it clearly states that null is not valid. I can therefore check this during coding, and not to stumble across it during code execution.

No comments:

Post a Comment