Recipe 9.11 Roll Your Own Exceptions


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


Go ahead and subclass Exception or RuntimeException.


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.

Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: