Java Reference
In-Depth Information
public class DreadfulProblemException extends Exception {
// Constructors
public DreadfulProblemException(){ } // Default constructor
public DreadfulProblemException(String s) {
super(s); // Call the base class constructor
}
// Constructor providing for chained exceptions
public DreadfulProblemException(String s, Throwable cause) {
super(s, cause);
// Call the base class constructor
}
}
The exception chaining capability is built into the base class because it is defined in
Throwable
. There-
fore you can just pass the
Throwable
argument that is passed to your constructor to the base class construct-
or.
Even when you have not provided a constructor in your exception class that accepts a
Throwable
ref-
erence, you can still chain your exception object to the exception that caused your exception to be thrown.
Your exception class inherits the
initCause()
method from
Throwable
that accepts an argument of type
Throwable
. Calling this method chains your exception to the previous exception. Note that you can only
call this method for an exception once, and you must not call it at all if you created your exception object
with a
Throwable
cause argument. The
initCause()
method will throw
IllegalStateException
if either
is the case. It will also throw
IllegalArgumentException
if you pass a reference to your exception object
as the argument; an exception cannot be its own cause.
Throwing Your Own Exception
As you saw earlier, you throw an exception with a statement that consists of the
throw
keyword, followed
by an exception object. This means you can throw your own exception in a method with the following state-
ments:
DreadfulProblemException e = new DreadfulProblemException();
throw e;
The method ceases execution at this point — unless the preceding code snippet is in a
try
block with
a
catch
block that catches this exception. The exception will be thrown to the calling program if it is not
caught. The message in the exception object consists only of the qualified name of the exception class.
If you want to add a specific message to the exception, you could define it as:
DreadfulProblemException e = new DreadfulProblemException("Uh-Oh, trouble.");
You're using a different constructor here. In this case the message stored in the superclass is a string that
consists of the class name with the string passed to the constructor appended to it. The
getMessage()
meth-
od inherited from
Throwable
, therefore, returns a
String
object containing the following string:
"DreadfulProblemException: Uh-Oh, trouble."
You can also create an exception object and throw it in a single statement. For example: