Java Reference
In-Depth Information
12.4 More on Exception Handling
A handler for an exception is found by propagating the exception backward through a
chain of method calls, starting from the current method.
Key
Point
The preceding sections gave you an overview of exception handling and introduced sev-
eral predefined exception types. This section provides an in-depth discussion of exception
handling.
Java's exception-handling model is based on three operations: declaring an exception ,
throwing an exception , and catching an exception , as shown in FigureĀ 12.2.
Declare exception
method1() {
method2() throws Exception {
try {
invoke method2;
if (an error occurs) {
}
catch (Exception ex) {
Process exception;
throw new Exception();
Throw exception
}
}
Catch exception
}
}
F IGURE 12.2
Exception handling in Java consists of declaring exceptions, throwing exceptions, and catching and
processing exceptions.
12.4.1 Declaring Exceptions
In Java, the statement currently being executed belongs to a method. The Java interpreter
invokes the main method to start executing a program. Every method must state the types of
checked exceptions it might throw. This is known as declaring exceptions . Because system
errors and runtime errors can happen to any code, Java does not require that you declare
Error and RuntimeException (unchecked exceptions) explicitly in the method. However,
all other exceptions thrown by the method must be explicitly declared in the method header so
that the caller of the method is informed of the exception.
To declare an exception in a method, use the throws keyword in the method header, as in
this example:
declare exception
public void myMethod() throws IOException
The throws keyword indicates that myMethod might throw an IOException . If the method
might throw multiple exceptions, add a list of the exceptions, separated by commas, after
throws :
public void myMethod()
throws Exception1, Exception2, ..., ExceptionN
Note
If a method does not declare exceptions in the superclass, you cannot override it to
declare exceptions in the subclass.
12.4.2 Throwing Exceptions
A program that detects an error can create an instance of an appropriate exception type and
throw it. This is known as throwing an exception . Here is an example: Suppose the program
detects that an argument passed to the method violates the method contract (e.g., the argument
throw exception
 
 
 
Search WWH ::




Custom Search