MODULE 3
Exception Handling
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. In computer languages that do not support
exception handling, errors must be checked and handled manually—typically through the use
of error codes, and so on.
Java’s exception handling avoids these problems and, brings run-time error management into
the object-oriented world.
Exception-Handling Fundamentals:
• A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
• When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
• That method may choose to handle the exception itself, or pass it on.
• Either way, at some point, the exception is caught and processed.
• Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
• Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.
Try: 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.
Catch: Your code can catch this exception (using catch) and handle it. System-generated
exceptions are automatically thrown by the Java run-time system.
Throw: To manually throw an exception, use the keyword throw.
Throws: Any exception that is thrown out of a method must be specified by a throws clause.
Finally: Any code that absolutely must be executed after a try block completes is put in a
finally block.
1
Exception Types:
2
1. Throwable:
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.
2. 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.
3. Error:
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.
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;
}
}
3
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 stop, because once an exception has been thrown, it must
be caught by an exception handler and dealt with immediately.
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.
Here is the exception generated when this example is executed:
[Link]: / by zero
at [Link]([Link])
• Notice how the class name, Exc0; the method name, main; the filename, [Link]; and the
line number, 4, are all included in the simple stack trace.
• Also, notice that the type of exception thrown is a subclass of Exception called
ArithmeticException, which more specifically describes what type of error happened.
• Java supplies several built-in exception types that match the various sorts of run-time errors
that can be generated.
• The stack trace will always show the sequence of method invocations that led up to the error.
• For example, here is another version of the preceding program that introduces the same error
but in a method separate from main( ):
• The resulting stack trace from the default exception handler shows how the entire call stack is
displayed:
4
• The bottom of the stack is main’s line 7, which is the call to subroutine( ), which caused the
exception at line 4.
• The call stack is quite useful for debugging, because it pinpoints the sequence of steps that led
to the error.
Using try and catch:
• Although the default exception handler provided by the Java run-time system is useful for
debugging, programmer may want to handle an exception.
• Doing so provides two benefits.
• First, it allows you to fix the error.
• Second, it prevents the program from automatically terminating.
• To handle a run-time error, simply enclose the code that you want to monitor inside a try
block.
• Immediately following the try block, include a catch clause that specifies the exception type
that you wish to catch.
The following program includes a try block and a catch clause that processes the
ArithmeticException generated by the division-by-zero error:
5
• The goal of most well-constructed catch clauses should be, to resolve the exceptional
condition and then continue on as if the error had never happened.
• For example, in the next program each iteration of the for loop obtains two random integers.
• Those two integers are divided by each other, and the result is used to divide the value 12345.
The final result is put into a.
• If either division operation causes a divide-by-zero error, it is caught, the value of a is set to
zero, and the program continues.
6
Displaying a Description of an Exception:
You can display this description of the exception in a println( ) statement by simply passing
the exception as an argument.
For example, the catch block in the preceding program can be rewritten like this:
catch (ArithmeticException e) {
[Link]("Exception: " + e);
a = 0; // set a to zero and continue
}
The divide-by-zero error displays the following message:
Exception: [Link]: / by zero
Multiple catch clauses:
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each catching a
different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after the
try / catch block.
The following example traps two different exception types:
When you use multiple catch statements, it is important to remember that exception subclasses
must come before any of their superclasses.
Subclass would never be reached if it came after its superclass.
Further, in Java, unreachable code is an error.
For example, consider the following program:
To fix the problem, reverse the order of the catch statements.
7
Nested try Statements:
• The try statement can be nested.
• That is, a try statement can be inside the block of another try.
• If an inner try statement does not have a catch handler for a particular exception, the next try
statement’s catch handlers are inspected for a match.
• This continues until one of the catch statements succeeds.
• If no catch statement matches, then the Java run-time system will handle the exception.
• Here is an example that uses nested try statements:
8
Output: ArrayIndexOutOfBoundsException
Element at such index does not exist
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.`
• The flow of execution stops immediately after the throw statement; any subsequent statements
are not executed.
9
• 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.
Output:
Caught inside demoproc.
Recaught: [Link]: demo
10
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.
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.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method }
11
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.
The finally clause is optional.
However, each try statement requires at least one catch or a finally clause.
Here is an example program that shows three methods that exit in various ways, but executing
their finally clauses:
import [Link].*;
class Fin {
public static void main(String[] args)
{
try {
[Link]("inside try block");
[Link](34 / 2);
}
catch (ArithmeticException e) { // Not execute in this case
[Link]("Arithmetic Exception");
}
// Always execute
finally {
[Link]("finally : will always execute.");
}
}
}
12
Creating Your Own Exception Subclasses /Custom
Exceptions:
Although Java’s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications.
This is quite easy to do: just define a subclass of Exception.
The Exception class does not define any methods of its own.
It inherits those methods provided by Throwable.
Few examples are shown in Table.
You may also wish to override one or more of these methods in exception classes that you
create.
13
Table 10-3 The Methods Defined by Throwable
class MyException extends Exception {
public MyException(String m) {
super(m);
} }
public class setText {
public static void main(String args[ ]) {
try {
throw new MyException("This is a custom exception");
14
}
catch (MyException ex) {
[Link]("Caught");
[Link]([Link]());
}
}
}
Output:
Caught
This is a custom exception
15