Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata