Java Reference
In-Depth Information
•
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 only do this when the way the exception is handled will
vary from one invocation of the method to another. There is seldom any other sit-
uation 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 descen-
dent of
the
class
Error
), the exception type must be listed in the
throws
clause for
that method.
Answers to Self-Test Exercises
1.
Try block entered.
Over 30.
After catch block
2.
The output would then be
Try block entered.
Under 30.
After catch block
3.
There are two
throw
statements:
throw new
Exception("Over 30.");
throw new
Exception("Under 30.");
4. When a
throw
statement is executed, that is the end of the enclosing
try
block.
No other statements in the
try
block are executed, and control passes to the fol-
lowing
catch
block(s). When we say that control passes to the following
catch
block, we mean that the exception object that is thrown is plugged in for the
catch
block parameter and the code in the
catch
block is executed.
5.
try
{
System.out.println("Try block entered.");
if
(waitTime > 30)
throw new
Exception("Over 30.");
else if
(waitTime < 30)
throw new
Exception("Under 30.");
else
System.out.println("No exception.");
System.out.println("Leaving try block.");
}