Java Reference
In-Depth Information
11
public static void
method1()
throws
Exception {
12
try
{
13 method2();
14 }
15
catch
(Exception ex) {
throw new
Exception(
"New info from method1"
, ex);
chained exception
16
17 }
18 }
19
20
public static void
method2()
throws
Exception {
21
22 }
23 }
throw new
Exception(
"New info from method2"
);
throw exception
java.lang.Exception: New info from method1
at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:16)
at ChainedExceptionDemo.main(ChainedExceptionDemo.java:4)
Caused by: java.lang.Exception: New info from method2
at ChainedExceptionDemo.method2(ChainedExceptionDemo.java:21)
at ChainedExceptionDemo.method1(ChainedExceptionDemo.java:13)
... 1 more
The
main
method invokes
method1
(line 4),
method1
invokes
method2
(line 13), and
method2
throws an exception (line 21). This exception is caught in the
catch
block in
method1
and is wrapped in a new exception in line 16. The new exception is thrown and
caught in the catch block in the
main
method in line 6. The sample output shows the output
from the
printStackTrace()
method in line 7. The new exception thrown from
method1
is displayed first, followed by the original exception thrown from
method2
.
You can define a custom exception class by extending the
java.lang.Exception
class.
Key
Point
Java provides quite a few exception classes. Use them whenever possible instead of defining
your own exception classes. However, if you run into a problem that cannot be adequately
described by the predefined exception classes, you can create your own exception class,
derived from
Exception
or from a subclass of
Exception
, such as
IOException
.
In Listing 14.7, CircleWithException.java, the
setRadius
method throws an exception if
the radius is negative. Suppose you wish to pass the radius to the handler. In that case, you can
define a custom exception class, as shown in Listing 14.10.
VideoNote
Create custom exception
classes
L
ISTING
14.10
InvalidRadiusException.java
1
public class
InvalidRadiusException
extends
Exception
{
extends
Exception
2
private double
radius;
3
4
/** Construct an exception */
5
public
InvalidRadiusException(
double
radius)
{
6
super
(
"Invalid radius "
+ radius);
7
this
.radius = radius;
8 }
9
10
/** Return the radius */
11
public double
getRadius() {
12
return
radius;
13 }
14 }