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.
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.