img
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred. The remainder of this chapter
describes how to apply this framework.
Exception Types
All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the
top of the exception class hierarchy. Immediately below Throwable are two subclasses that
partition exceptions into two distinct branches. One branch is headed by Exception. This class
is used for exceptional conditions that user programs should catch. This is also the class that
you will subclass to create your own custom exception types. There is an important subclass
of Exception, called RuntimeException. Exceptions of this type are automatically defined for
the programs that you write and include things such as division by zero and invalid array
indexing.
The other branch is topped by Error, which defines exceptions that are not expected to
be caught under normal circumstances by your program. Exceptions of type Error are used
by the Java run-time system to indicate errors having to do with the run-time environment,
itself. Stack overflow is an example of such an error. This chapter will not be dealing with
exceptions of type Error, because these are typically created in response to catastrophic failures
that cannot usually be handled by your program.
Uncaught Exceptions
Before you learn how to handle exceptions in your program, it is useful to see what happens
when you don't handle them. This small program includes an expression that intentionally
causes a divide-by-zero error:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of Exc0 to
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home