Java Reference
In-Depth Information
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 re-
quired to catch or “throw upward” by listing them in the
throws
clause of the invoking
method.
When subclassing either of these, it is customary to provide at least these constructors:
▪ A no-argument constructor
▪ A one-string argument constructor
▪ A two argument constructor—a string message and a
Throwable
“cause”
The “cause” will appear if the code receiving the exception performs a stack trace operation
on it, with the prefix “Root Cause is” or similar.
Example 8-6
shows these three constructors
for an application-defined exception,
ChessMoveException:
.
Example 8-6. oo/ChessMoveException.java
/** A ChessMoveException is thrown when the user makes an illegal move. */
public
public class
class
ChessMoveException
ChessMoveException
extends
extends
Exception
{
private
private static
static final
final
long
long
serialVersionUID
=
802911736988179079L
;
public
public
ChessMoveException
() {
super
super
();
}
public
public
ChessMoveException
(
String msg
) {
super
super
(
msg
);
}
public
public
ChessMoveException
(
String msg
,
Exception cause
) {
super
super
(
msg
,
cause
);
}
}