Java Reference
In-Depth Information
Here's an example using a hypothetical NotInServiceException class that is a subclass
of the Exception class:
NotInServiceException nise = new NotInServiceException();
throw nise;
You can throw only objects that implement the Throwable interface.
Depending on the exception class you're using, the exception also may have arguments
to its constructor that you can use. The most common of these is a string argument,
which enables you to describe the problem in greater detail (which can be useful for
debugging purposes). Here's an example:
NotInServiceException nise = new
NotInServiceException(“Exception: Database Not in Service”);
throw nise;
After an exception is thrown, the method exits immediately without executing any other
code, other than the code inside a finally block if one exists. The method won't return
a value either. If the calling method does not have a try or catch surrounding the call to
your method, the program might exit based on the exception you threw.
Creating Your Own Exceptions
Although there are a fair number of exceptions in the Java class library that you can use
in your own methods, you might need to create your own exceptions to handle the differ-
ent kinds of errors that your programs run into. Creating new exceptions is easy.
Your new exception should inherit from some other exception in the Java hierarchy. All
user-created exceptions should be part of the Exception hierarchy rather than the Error
hierarchy, which is reserved for errors involving the Java virtual machine. Look for an
exception that's close to the one you're creating; for example, an exception for a bad file
format would logically be an IOException . If you can't find a closely related exception
for your new exception, consider inheriting from Exception , which forms the “top” of
the exception hierarchy for checked exceptions (unchecked exceptions should inherit
from RuntimeException ).
Exception classes typically have two constructors: The first takes no arguments, and the
second takes a single string as an argument.
Exception classes are like other classes. You can put them in their own source files and
compile them just as you would other classes:
public class SunSpotException extends Exception {
public SunSpotException() {}
Search WWH ::




Custom Search