Java Reference
In-Depth Information
The section titled Java Exception Hierarchy describes the hierarchy of Java's various
built-in exception classes. The section titled Java's Exception Classes describes some
of the built-in exception classes and their methods. Both sections appear later in this
chapter.
Statements that might generate an exception are placed in a
try
block. The
try
block
might also contain statements that should not be executed if an exception occurs. The
try
block is followed by zero or more
catch
blocks. A
catch
block specifies the type of
exception it can catch and contains an exception handler. The last
catch
block may or
may not be followed by a
finally
block. Any code contained in a
finally
block
always executes, regardless of whether an exception occurs, except when the program
exits early from a
try
block by calling the method
System.exit
.Ifa
try
block has no
catch
block, then it must have the
finally
block.
As noted previously, when an exception occurs, Java creates an object of a specific
exception class. For example, if a division by zero exception occurs, then Java creates
an object of the
ArithmeticException
class
.
The general syntax of the
try
/
catch
/
finally
block is:
try
{
//statements
}
catch
(ExceptionClassName1 objRef1)
{
//exception handler code
}
catch
(ExceptionClassName2 objRef2)
{
//exception handler code
}
...
catch
(ExceptionClassNameN objRefN)
{
//exception handler code
}
finally
{
//statements
}
(A
try
block contains code for normal circumstances, while a
catch
block contains code
to handle an exception(s).)
Search WWH ::
Custom Search