Java Reference
In-Depth Information
The
try
Statement
A
try statement
is a block of code that contains one or more statements that may throw
an exception. A
try
statement can be followed by one or more
catch clauses
, also called
exception handlers. Figure 3.10 shows the syntax of a
try
statement.
The syntax of a
try
statement
FIGURE 3.10
If an exception is thrown in a try
statement, the catch clauses
attempt to catch it.
The try keyword
try {
The identifier refers to
the caught exception
object.
//The try block is also referred to
//as protected code
} catch (
exception_type identifier
) {
//exception handler
Curly braces are
required.
}
The type of
exception you are
trying to catch
The catch keyword
A
try
statement can declare any number of
catch
clauses. A
catch
clause must have
exactly one parameter: the data type of the exception trying to be caught. If an exception
is thrown within a
try
block, the JVM searches for a handler by checking the exception
types of its
catch
clauses in the order they appear. If the exception type of a
catch
clause
matches the data type of the thrown exception, fl ow of control jumps to that
catch
block
and the
catch
's identifi er receives a copy of the reference to the exception object (similar to
an argument copied into a method parameter).
For example, the following
try
statement catches the
ArithmeticException
thrown in
method3
of the
ExceptionDemo
class from the previous section. See if you can determine the
output of running
main
in
ExceptionDemo
if
method3
is modifi ed as follows:
12. public void method3() {
13. System.out.println(“Inside method3”);
14. int x = 5, y = 0;
15. try {
16. int z = x/y; //throws an ArithmeticException
17. System.out.println(“z = “ + z);
18. }catch(ArithmeticException e) {
19. System.out.println(“Something went wrong: “
20. + e.getMessage());
21. }
23. }
Search WWH ::
Custom Search