Home » Uncategorized

Putting RuntimeExceptions in the Throws Clause

16 April 2004 No Comment

Many people (including myself) advocate using only RuntimeExceptions (unchecked exceptions) in Java. Many people tend to dislike checked exceptions because they can cause problems with coupling, they clutter code with try-catch blocks, and they are often wrapped and forgotten (when a developer doesn’t do anything with the exception besides catching it).

I’ve been involved in many debates discussing the pros and cons of using only unchecked exceptions. The strongest argument that I’ve heard against using unchecked exceptions goes something like this:

“Java advocates using checked exceptions for recoverable exceptions and unchecked exceptions for unrecoverable exceptions. Using this approach, I don’t mind letting unrecoverable, unchecked exceptions propogate up to a top-level exception handler, because I can’t recover from them anyways. But, I would need to know when a recoverable unchecked exception is thrown so that I can decide if and how to handle it from the calling method. Its not fair for me to have to look up the documentation for a method every time I want to find out if it throws a recoverable unchecked exception, thus I’ll stick with checked exceptions.”

This is a very valid point. It would be very helpful if a developer had an easier way to see what the error handling “contract” is so that he can make the correct decision on where and how to handle it. So how can one make it easier for somebody using an API to see the exception handling contract for a method. One technique I’ve been trying is including all recoverable RuntimeExceptions that a method throws in its throws clause.

What is the benefit of this? Well for one, it prevents the developer from having to look up the JavaDoc for a method just to see if there is a recoverable RuntimeException that is thrown by the method that they call. Second, an IDE could (in the future) provide support to show a user what exceptions are in the throws clause of a method call using a hover-over dialog box and/or by highlighting methods that have RuntimeExceptions in their throws clauses but that are not wrapped in a try-catch block.

I am still just experimenting with this idea, and I have yet to get feedback on it from other developers. I’d be interested in hearing what other people have to say about it.

Here is an example:

public class ExceptionExample
public class MyRecoverableException
extends RuntimeException { }
public class MyUnrecoverableException
extends RuntimeException { }

public static void main(String[] args)
ExceptionExample example = new ExceptionExample();

try {
catch (MyRecoverableException e) {
"Good thing I saw that throws clause!" );

System.out.println( "I won't get here!" );

public void methodA()
throws MyRecoverableException {
throw new MyRecoverableException();

public void methodB() {
throw new MyUnrecoverableException();

Comments are closed.