Java Reference
In-Depth Information
thing to do. The
AssertionError
class is in the
java.lang
package and so requires
no import statement.
As the name suggests, the class
AssertionError
is derived from the class
Error
, so
you are not required to either catch it in a
catch
block or declare it in a
throws
clause.
Read Section 6.1 of Chapter 6 , which covers array basics, before reading this short
subsection. If you have not yet covered some of Chapter 6, omit this section and return
to it at a later time.
If your program attempts to use an array index that is out of bounds, an
ArrayIndexOutOfBoundsException
is thrown and your program ends, unless the
exception is caught in a
catch
block.
ArrayIndexOutOfBoundsException
is a
descendent of the class
RuntimeException
and so need not be caught or accounted for
in a
throws
clause. This sort of exception normally indicates that there is something
wrong with your code and means that you need to fix your code, not catch an
exception. Thus, an
ArrayIndexOutOfBoundsException
normally functions more
like a run-time error message than a regular exception.
ArrayIndexOutOfBoundsException
is in the standard Java package
java.lang
and so requires no import statement should you decide to use it by name.
Chapter Summary
•
Exception handling allows you to design and code the normal case for your program
separately from the code that handles exceptional situations.
•
An exception can be thrown in a
try
block
. Alternatively, an exception can be thrown
in a method definition that does not include a
try
block (or does not include a
catch
block to catch that type of exception). In this case, an invocation of the method can
be placed in a
try
block.
•
An exception is caught in a
catch
block
.
•
A
try
block must be followed by at least one
catch
block and can be followed by
more than one
catch
block. If there are multiple
catch
blocks, always list the
catch
block for a more specific exception class before the
catch
block for a more general
exception class.
•
The best use of exceptions is to throw an exception in a method (but not catch it in
the method)—but to do this only when the way the exception is handled will vary
from one invocation of the method to another. There is seldom any other situation
that can profitably benefit from throwing an exception.
•
If an exception is thrown in a method but not caught in that method, then if
the exception is not a descendent of the class
RuntimeException
(and is not a
descendent of the class
Error
), the exception type must be listed in the
throws
clause for that method.