Java Reference
In-Depth Information
1.
Write a program that generates exceptions of type
NullPointerException
,
NegativeArraySizeEx-
ception
, and
IndexOutOfBoundsException
. Record the catching of each exception by displaying the
message stored in the exception object and the stack trace record.
2.
Add an exception class to the last example that differentiates between the index-out-of-bounds error
possibilities, rethrows an appropriate object of this exception class in
divide()
, and handles the excep-
tion in
main()
.
3.
Write a program that calls a method that throws an exception of type
ArithmeticException
at a ran-
dom iteration in a
for
loop. Catch the exception in the method and pass the iteration count when the ex-
ception occurred to the calling method by using an object of an exception class you define.
4.
Add a
finally
block to the method in the previous example to output the iteration count when the
method exits.
• WHAT YOU LEARNED IN THIS CHAPTER
TOPIC CONCEPT
ExceptionsExceptions identify abnormal errors that arise in your program. Exceptions are objects of subclasses of the
Throwable
class.
Standard
Exceptions
Java includes a set of standard exceptions that may be thrown automatically, as a result of errors in your
code, or may be thrown by methods in the standard classes in Java.
Uncaught
Exceptions
If a method throws exceptions that aren't caught, and aren't represented by subclasses of the
Error
class or
the
RuntimeException
class, then you must identify the exception classes in a
throws
clause in the meth-
od definition.
Catching
Exceptions
If you want to handle an exception in a method, you must place the code that may generate the exception in
a
try
block. A method may have several
try
blocks.
Exception handling code is placed in a
catch
block that immediately follows the
try
block that contains
the code that can throw the exception. A
try
block can have multiple
catch
blocks that each deals with a
different type of exception.
catch
Blocks
A
finally
block is used to contain code that must be executed after the execution of a
try
block, regard-
less of how the
try
block execution ends. A
finally
block is always executed before execution of the
method ends.
finally
Blocks
Throwing
Exceptions
You can throw an exception by using a
throw
statement. You can throw an exception anywhere in a meth-
od. You can also rethrow an existing exception in a
catch
block to pass it to the calling method.
Defining
Exceptions
You can define your own exception classes. In general, your exceptions classes should be derived from the
Exception
class to ensure that they are checked exceptions. The compiler ensures that all checked excep-
tions are dealt with in the code where such exceptions may be thrown.
Chained
Exceptions
When you throw a new exception in a
catch
block, you can record the previous exception by creating your
exception object to store a reference to the previous exception or by calling
initCause()
for your new ex-
ception object.