Java Reference
In-Depth Information
an extension of some existing exception class that stores a particular message
describing the situation it represents. The important point is that the class is ulti-
mately a descendant of the
Exception
class and the
Throwable
class, which gives
it the ability to be thrown using a
throw
statement.
The type of situation handled by this program, in which a value is out of range,
does not need to be represented as an exception. We've previously handled such
situations using conditionals or loops. Whether you handle a situation using an
exception or whether you take care of it in the normal flow of your program is
an important design decision.
Checked and Unchecked Exceptions
Some exceptions are checked, whereas others are unchecked. A
checked excep-
tion
must either be caught by a method or it must be listed in the
throws clause
of any method that may throw or propagate it. A
throws
clause is appended to
the header of a method definition to formally acknowledge that the method will
throw or propagate a particular exception if it occurs. An
unchecked exception
requires no
throws
clause.
The only unchecked exceptions in Java are objects of type
RuntimeException
or any of its descendants. All other excep-
tions are considered checked exceptions. The
main
method of the
CreatingExceptions
program has a
throws
clause, indicating that it
may throw an
OutOfRangeException
. This
throws
clause is required
because the
OutOfRangeException
was derived from the
Exception
class, making it a checked exception.
KEY CONCEPT
The
throws
clause on a method
header must be included for checked
exceptions that are not caught and
handled in the method.
SELF-REVIEW QUESTIONS
(see answers in Appendix N)
SR 11.10
What is a checked exception?
SR 11.11
True or False? Explain.
a. An
ArithmeticException
is an
Exception
.
b. An
ArithmeticException
is
Throwable
.
c. An
ArithmeticException
is a checked exception.
d. A
NoSuchMethodException
is a checked exception.
e. We can create our own exceptions by extending the
Exception
class.
f. A
throws
clause must be appended to the header of a
method definition if the method may potentially throw an
ArithmeticException
.
SR 11.12
What happens if the input to the
CreatingExceptions
program is
42? What if it is −3?
Search WWH ::
Custom Search