Module-4 (Exception Handling)
Module-4 (Exception Handling)
CHAPTER-2
Exceptions
An exception is an abnormal condition that arises in a code sequence at run
time. In other words, an exception is a run time error
Exception-Handling Fundamentals
Java exception handling is managed via five keywords: try, catch,
throw, throws, and finally.
Program statements that you want to monitor for exceptions are
contained within a try block.
If an exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch) and handle it in some
rational manner.
System-generated exceptions are automatically thrown by the Java
run time system.
To manually throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be specified as such by
a throws clause.
Any code that absolutely must be executed after a try block completes is
put in a finally block.
Exception Types
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.
we haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java run-
time system.
Any exception that is not caught by your program will ultimately be
processed by the default handler.
The default handler displays a string describing the exception, prints
a stack trace from the point at which the exception occurred, and
terminates the program.
throw
So far, you have only been catching exceptions that are thrown by the
Java run-time system.
However, it is possible for your program to throw an exception
explicitly, using the throw statement.
The general form of throw is shown here: throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a
subclass of Throwable.
Primitive types, such as int or char, as well as non-Throwable
classes, such as String and Object, cannot be used as exceptions.
There are two ways you can obtain a Throwable object: using a
parameter in a catch clause or creating one with the new operator.
The flow of execution stops immediately after the throw statement;
any subsequent statements are not executed.
The nearest enclosing try block is inspected to see if it has a catch
statement that matches the type of exception.
If it does find a match, control is transferred to that statement. If
not, then the next enclosing try statement is inspected, and so on. If
no matching catch is found, then the default exception handler halts
the program and prints the stack trace.
Here is a sample program that creates and throws an exception. The
handler that catches the exception rethrows it to the outer handler.
Throws
If a method is capable of causing an exception that it does not handle, it
must specify this behavior so that callers of the method can guard
themselves against that exception.
You do this by including a throws clause in the method’s declaration.
A throws clause lists the types of exceptions that a method might
throw. This is necessary for all exceptions, except those of type Error
or RuntimeException, or any of their subclasses.
All other exceptions that a method can throw must be declared in the
throws clause. If they are not, a compile-time error will result.
finally
finally creates a block of code that will be executed after a try /catch
block has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.
If an exception is thrown, the finally block will execute even if no
catch statement matches the exception.
Any time a method is about to return to the caller from inside a try/catch
block, via an uncaught exception or an explicit return statement, the
finally clause is also executed just before the method returns.
This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a method
with the intent of disposing of them before returning.
The finally clause is optional.
However, each try statement requires at least one catch or a finally clause
In the first form, causeExc is the exception that causes the current
exception.
That is, causeExc is the underlying reason that an exception occurred.
The second form allows you to specify a description at the same time
that you specify a cause exception.
These two constructors have also been added to the Error, Exception,
and RuntimeException classes.
The chained exception methods supported by Throwable are
getCause( ) and initCause( ).
These methods are shown in Table 10-3 and are repeated here for the
sake of discussion.
The getCause( ) method returns the exception that underlies the current
exception.
If there is no underlying exception, null is returned.
The initCause( ) method associates causeExc with the invoking
exception and returns a reference to the exception.
Thus, you can associate a cause with an exception after the exception has
been created.
However, the cause exception can be set only once.
Thus, you can call initCause( ) only once for each exception object.
Furthermore, if the cause exception was set by a constructor, then you
can’t set it again using initCause( ).
In general, initCause( ) is used to set a cause for legacy exception
classes that don’t support the two additional constructors described
earlier.
Here is an example that illustrates the mechanics of handling chained
exceptions: