Trail: Essential Java Classes
|
Lesson: Handling Errors with Exceptions
|
|
How to Throw Exceptions
The pages listed below explain how to throw exceptions in
a Java program.
Before you can catch an exception, some Java code somewhere must
throw one. Any Java code can throw an exception: your code, code
from a package written by someone else (such as the packages that
come with the Java development environment), or the Java runtime
system. Regardless of who (or what) throws the exception, it's
always thrown with the Java throw statement.
The Java language requires that exceptions derive from the Throwable
class or one of its subclasses.
As you have undoubtedly noticed in your travels (travails?) through the
Java language, the packages that ship with the Java development environment
provide numerous exception classes. All of these classes are
descendants of the Throwable class and allow programs to differentiate
between the various types of exceptions that can occur during
the execution of a Java program.
You can create your own exception classes, as well, to represent problems
that can occur within the classes that you write. Indeed, if you are a package
developer you will find that you must create your own set of exception
classes to allow your users to differentiate an error that can occur
in your package versus those errors that occur in the Java development
environment or other packages.
|