O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Roll Your Own Exceptions

Problem

You’d like to use an application-specific exception class or two.

Solution

Go ahead and subclass Exception or RuntimeException.

Discussion

In theory you could subclass Throwable directly, but that’s considered rude. You normally subclass Exception (if you want a checked exception) or RuntimeException (if you want an unchecked exception). Checked exceptions are those that an application developer is required to catch, or “throw away” by listing them in the throws clause of the invoking method.

When subclassing either of these, it is customary to provide at least a no-argument and a one-string argument constructor:

/** A ChessMoveException is thrown  when the user makes an illegal move. */
public class ChessMoveException extends RuntimeException {
        public ChessMoveException (  ) {
                super(  );
        }
        public ChessMoveException (String msg) {
                super(msg);
        }
}

See Also

The Javadoc documentation for Exception lists a very large number of subclasses; you might look there first to see if there is one you can use.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required