Java Reference
In-Depth Information
must be nonnegative, but a negative argument is passed); the program can create an instance
of
IllegalArgumentException
and throw it, as follows:
IllegalArgumentException ex =
new
IllegalArgumentException(
"Wrong Argument"
);
throw
ex;
Or, if you prefer, you can use the following:
throw new
IllegalArgumentException(
"Wrong Argument"
);
Note
IllegalArgumentException
is an exception class in the Java API. In general,
each exception class in the Java API has at least two constructors: a no-arg con-
structor, and a constructor with a
String
argument that describes the exception.
This argument is called the
exception message
, which can be obtained using
getMessage()
.
exception message
Tip
The keyword to declare an exception is
throws
, and the keyword to throw an exception
is
throw
.
throws
vs.
throw
14.4.3 Catching Exceptions
You now know how to declare an exception and how to throw an exception. When an excep-
tion is thrown, it can be caught and handled in a
try-catch
block, as follows:
catch exception
try
{
statements;
// Statements that may throw exceptions
}
catch
(Exception1 exVar1) {
handler for exception1;
}
catch
(Exception2 exVar2) {
handler for exception2;
}
...
catch
(ExceptionN exVar3) {
handler for exceptionN;
}
If no exceptions arise during the execution of the
try
block, the
catch
blocks are skipped.
If one of the statements inside the
try
block throws an exception, Java skips the
remaining statements in the
try
block and starts the process of finding the code to handle
the exception. The code that handles the exception is called the
exception handler
; it is
found by
propagating the exception
backward through a chain of method calls, starting
from the current method. Each
catch
block is examined in turn, from first to last, to see
whether the type of the exception object is an instance of the exception class in the
catch
block. If so, the exception object is assigned to the variable declared, and the code in the
catch
block is executed. If no handler is found, Java exits this method, passes the excep-
tion to the method that invoked the method, and continues the same process to find a han-
dler. If no handler is found in the chain of methods being invoked, the program terminates
and prints an error message on the console. The process of finding a handler is called
catching an exception
.
exception handler
exception propagation