Java Reference
In-Depth Information
The first line of the exception output indicates which excep-
tion was thrown and provides some information about why it was
thrown. The remaining lines are the
call stack trace
; they indicate
where the exception occurred. In this case, there is only one line in
the call stack trace, but there may be several depending on where
the exception originated. The first trace line indicates the method,
file, and line number where the exception occurred. The other trace lines, if pres-
ent, indicate the methods that were called to get to the method that produced the
exception. In this program, there is only one method, and it produced the excep-
tion; therefore there is only one line in the trace.
The call stack trace information is also available by calling methods of the
exception class that is being thrown. The method
getMessage
returns a string
explaining the reason the exception was thrown. The method
printStackTrace
prints the call stack trace.
KEY CONCEPT
The messages printed when an
exception is thrown provide a
method call stack trace.
SELF-REVIEW QUESTION
(see answer in Appendix N)
SR 11.3
True or False. Explain.
a. An exception and an error are the same thing.
b. An attempt to divide by zero will cause an exception to be thrown.
c. If a program does not handle a raised exception, the exception is
ignored and nothing happens.
d. If a program does not handle an exception, a message related to
the exception will be produced.
e. A call stack trace shows the sequence of method calls that led to
the code where an exception occurred.
11.3
The
try-catch
Statement
Let's now examine how we catch and handle an exception when it is thrown.
The
try-catchstatement
identifies a block of statements that may throw an excep-
tion. A
catch clause
, which follows a
try
block, defines how a particular kind of
exception is handled. A
try
block can have several
catch
clauses associated with
it. Each
catch
clause is called an
exception handler.
When a
try
statement is executed, the statements in the
try
block are exe-
cuted. If no exception is thrown during the execution of the
try
block, processing
continues with the statement following the
try
statement (after all of the
catch
clauses). This situation is the normal execution flow and should occur most of
the time.
Search WWH ::
Custom Search