Java Reference
In-Depth Information
This catch block looks very much like a method definition that has a parameter
of a type Exception . By using the type Exception , this catch block will catch any
possible exception that is thrown. We will see at the end of this section that we can
also restrict the catch block to specific exception classes. The catch block is not a
method definition, but in some ways, it is like a method. It is a separate piece of code
that is executed when your code throws an exception. The catch block in the previous
example will print out a message about the exception that was thrown.
So, when an exception is thrown, it is similar to a method call, but instead of calling
a method, it calls the catch block and says to execute the code in the catch block.
A catch block is often referred to as an exception handler .
Let's focus on the identifier e in the following line from a catch block:
exception
handler
catch (Exception e)
catch block
parameter
That identifier e in the catch block heading is called the catch block parameter .
Each catch block can have at most one catch block parameter. The catch block
parameter does two things:
• The catch block parameter is preceded by an exception class name that specifies
what type of thrown exception object the catch block can catch. If the class name is
Exception , then the block can catch any exception.
• The catch block parameter gives you a name for the thrown object that is caught, so
you can write code in the catch block that does things with the thrown object that
is caught.
Although the identifier e is often used for the catch block parameter, this is not
required. You may use any nonkeyword identifier for the catch block parameter just as
you can for a method parameter.
catch Block Parameter
The catch block parameter is an identifier in the heading of a catch block that serves as a
placeholder for an exception that might be thrown. When a suitable exception is thrown in
the preceding try block, that exception is plugged in for the catch block parameter. The
identifier e is often used for catch block parameters, but this is not required. You can use
any legal (nonkeyword) identifier for a catch block parameter.
SYNTAX
catch ( Exception_Class_Name Catch_Block_Parameter )
{
Code to be performed if an exception of the named exception class is thrown in
the try block .
}
You may use any legal identifier for the Catch_Block_Parameter .
 
Search WWH ::




Custom Search