Java Reference
In-Depth Information
try
{
...
try
{
...
}
catch
(
}
catch
(
Exception ex
) {
RuntimeException ex
) {
...
...
}
catch
(
}
catch
(
RuntimeException ex
) {
Exception ex
) {
...
...
}
}
(a) Wrong order
(b) Correct order
Note
Java forces you to deal with checked exceptions. If a method declares a checked exception
(i.e., an exception other than
Error
or
RuntimeException
), you must invoke it in a
try-catch
block or declare to throw the exception in the calling method. For example,
suppose that method
p1
invokes method
p2
, and
p2
may throw a checked exception
(e.g.,
IOException
); you have to write the code as shown in (a) or (b) below.
catch or declare checked
exceptions
void
p1() {
void
p1()
throws
IOException
{
try
{
p2();
p2();
}
catch
(IOException ex)
{
}
...
}
}
(a) Catch exception
(b) Throw exception
Note
You can use the new JDK 7 multi-catch feature to simplify coding for the exceptions with
the same handling code. The syntax is:
JDK 7 multi-catch
catch
(Exception1 | Exception2 | ... | Exceptionk ex) {
// Code to handle exceptions
}
Each exception type is separated from the next with a vertical bar (
|
). If one of the
exceptions is caught, the handling code is executed.
14.4.4 Getting Information from Exceptions
An exception object contains valuable information about the exception. You may use the fol-
lowing instance methods in the
java.lang.Throwable
class to get information regarding
the exception, as shown in Figure 14.4. The
printStackTrace()
method prints stack trace
methods in
Throwable
java.lang.Throwable
+getMessage(): String
+toString(): String
Returns the message that describes this exception object.
Returns the concatenation of three strings: (1) the full name of the exception
class; (2)
":"
(a colon and a space); (3) the
getMessage()
method.
Prints the
Throwable
object and its call stack trace information on the
console.
Returns an array of stack trace elements representing the stack trace
+printStackTrace(): void
+getStackTrace():
StackTraceElement[]
pertaining to this exception object.
F
IGURE
14.4
Throwable
is the root class for all exception objects.