Java Reference
In-Depth Information
19
20
public static void method2() throws Exception {
21
throw new Exception( "New info from method2" );
throw exception
22 }
23 }
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 .
12.24
βœ“
βœ“
What would be the output if line 16 is replaced by the following line?
Check
Point
throw new Exception( β€œNew info from method1” );
12.9 Defining Custom Exception Classes
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 12.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 12.10.
VideoNote
Create custom exception
classes
L ISTING 12.10
InvalidRadiusException.java
1 public class InvalidRadiusException extends Exception {
2
extends Exception
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 }
This custom exception class extends java.lang.Exception (line 1). The Exception class
extends java.lang.Throwable . All the methods (e.g., getMessage() , toString() , and
 
 
 
Search WWH ::




Custom Search