Exception Handling
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 manuallytypically through the use of error codes, and so on. This approach is as
cumbersome as it is troublesome. Javas exception handling avoids these problems and, in the process,
brings run-time error management into the object-oriented world.
These errors are called exceptions because, presumably, they are not usual occurrences; they are
exceptional. Exception handling is the name for the object-oriented techniques to manage such errors.
Unplanned exceptions that occur during a programs execution are also called runtime exceptions.
Java has two basic classes of errors: Error and Exception. Both of these classes descend from the Throwable
class, as shown in figure 1.
Fig. 1
The Error class represents more serious errors from which your program usually cannot recover. Usually, you
do not use or implement Error objects in your programs. A program cannot recover from Error conditions on
its own.
The Exception class comprises less serious errors that represent unusual conditions that arise while a
program is running and from which the program can recover. The programs you write can generate many
types of potential exceptions, such as when you do the following:
You issue a command to read a file from a disk, but the file does not exist there.
You attempt to write data to a disk, but the disk is full or unformatted.
Your program asks for user input, but the user enters invalid data.
The program attempts to divide a value by 0.
The program tries to access an array with a subscript that is too large or too small.
If the JVM or run-time environment detects a semantic violation, then they implicitly throws an exception.
Alternately, a program can throw an exception explicitly using the throw statement. After an exception is
thrown, control is transferred from the current point of execution to an appropriate catch clause of an
enclosing try statement. The catch clause is called an exception handler because it handles the exception by
taking whatever actions are necessary to recover from it.
For example, consider the following example. It shows a class named Division that contains a single, small
main() method. The method declares three integers, prompts the user for values for two of them, and
calculates the value of the third integer by dividing the first two values.
import java.util.Scanner;
public class Division
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int denominator, numerator, result;
If the user enters 0 as the value for the denominator an Exception message
Arithmetic Exception: / by zero
is displayed.
Java does not allow integer division by 0, but floating-point division by 0 is allowedthe result displays as
Infinity.
Enter numerator >> 5
Enter denominator >> 0
5.0 / 0.0 = Infinity
If during some other execution, the users has entered noninteger data for the denominator say a string of
characters, or a floating-point value then a different type of Exception occurs. The Exception is an
InputMismatchException.
The list of error messages after each attempted execution is called a stack trace history list, or more simply, a
stack trace. The list shows each method that was called as the program ran.
These are examples of UNCAUGHT Exception. 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
Division to stop, because once an exception has been thrown, it must be caught by an exception handler and
dealt with immediately. In this example, we havent 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.
CHECKED EXCEPTION
These are the exceptions which occur during the compile time of the program. The compiler checks at the
compile time that whether the program contains handler for checked exceptions or not. These exceptions
extend the java.lang.Exception class; they should be anticipated and recovered by an application. Checked
exceptions are required to be caught. All the exceptions are checked exceptions unless and until those
indicated by Error, RuntimeException or their subclasses.
Example:
If we want to build a program that could read a file with a specific name then we would be prompted to input
a file name by the application. Then it passes the name to the constructor for java.io.FileReader and opens a
file. However if we provide the name of any non-existing file then the constructor throws
java.io.FileNotFoundException which abrupt the application to succeed. Hence this exception must be caught
by our application and will also prompt to correct the filename.
UNCHECKED EXCEPTION
These are the exceptions which occur during the run time of the program. Unchecked exceptions are internal
to the application and extend the java.lang.RuntimeException class. These exceptions cannot be anticipated
and recovered like programming bugs such as logic errors or improper use of an API. These types of exception
are also called Runtime exceptions that are usually caused by data error like array overflow, divide by zero
etc.
Example:
If we try to divide a number by zero then we get ArithmeticException. Similarly when an instance data
member or method of a reference variable is to be accessed that hasnt yet referenced an object throws
NullPointerException.
EXCEPTION HANDLING
Java exception handling is managed via five keywords:
try
catch
finally
throw
throws
TRY BLOCK
A try block encloses code that may give rise to one or more exceptions. Code that can throw an exception that
you want to catch must be in a try block.
A try block is simply the keyword try, followed by braces enclosing the code that can throw the exception:
try {
// Code that can throw one or more exceptions
}
Although I am discussing primarily exceptions that you must deal with here, a try block is also necessary if
you want to catch exceptions of type Error or RuntimeException. When we come to a working example, you
will use an exception type that you dont have to catch, simply because exceptions of this type are easy to
generate.
CATCH BLOCK
A catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in
the associated try block. You usually code at least one catch block immediately following a try block. The
exception might be one that is thrown automatically, or you might explicitly write a throw statement.
A catch block consists of the keyword catch followed by a single parameter between parentheses that identify
the type of exception that the block is to deal with. This is followed by the code to handle the exception
enclosed between braces:
try {
// Code that can throw one or more exceptions
} catch(ExceptionType exOb) {
// Code to handle the exception
}
If we specify the ExceptionType as ArithmeticException then the catch block can only handle exception of
that kind. This implies that this is the only kind of exception that can be thrown in the try block. If some
other exception is thrown, this wont compile.
In general, the parameter for a catch block must be of type Throwable or one of the subclasses of the class
Throwable. If the class that you specify as the parameter type has subclasses, the catch block will be expected
to process exceptions of that class type, plus all subclasses of the class.
import java.util.Scanner;
public class Division
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int denominator, numerator, result;
When this version is substituted in the program, and the program is run, each divide-by-zero error displays
the following message:
Exception: java.lang.ArithmeticException: / by zero
While it is of no particular value in this context, the ability to display a description of an exception is valuable
in other circumstancesparticularly when you are experimenting with exceptions or when you are debugging.
class Exception_1
{
public static void main(String ar[])
{
try
{
int a[] = new int[5];
int b = 30/0;
a[15] = 9;
}
catch(ArithmeticException ae)
{System.out.println("ArithmeticException");}
catch(ArrayIndexOutOfBoundsException ie)
{System.out.println("ArrayIndexOutOfBoundsException");}
catch(Exception e)
{System.out.println("Exception");}
System.out.println("Rest");
}
}
OUTPUT:
ArithmeticException
Rest
All catch blocks must be ordered from most specific to most general i.e., catch for ArithmeticException must
come before catch for Exception.
That is exception subclasses must come before any of their superclasses. This is because a catch statement
that uses a superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass would
never be reached if it came after its superclass.
class Exception_1
{
public static void main(String ar[])
{
try
{
int a[] = new int[5];
int b = 30/0;
a[15] = 9;
}
catch(Exception e)
{System.out.println("Exception");}
catch(ArithmeticException ae)
{System.out.println("ArithmeticException");}
catch(ArrayIndexOutOfBoundsException ie)
{System.out.println("ArrayIndexOutOfBoundsException");}
System.out.println("Rest");
}
}
OUTPUT:
Compile time error
class Exception_2
{
public static void main(String ar[])
{
try
{
int a[] = new int[5];
int b = 30/0; // int b = 30/5;
try{
a[15] = 9;
}
catch(ArrayIndexOutOfBoundsException ie)
{System.out.println("ArrayIndexOutOfBoundsException");}
}
catch(ArithmeticException ae)
{System.out.println("ArithmeticException");}
}
}
OUTPUT:
ArithmeticException / ArrayIndexOutOfBoundsException
Nesting of try statements can occur in less obvious ways when method calls are involved. For example, you
can enclose a call to a method within a try block. Inside that method is another try statement. In this case,
the try within the method is still nested inside the outer try block, which calls the method.
class Exception_2
{
public static void main(String ar[])
{
try {
int a[] = new int[5];
a[15] = 9; //a[4] = 9;
check(0);
}
catch(ArrayIndexOutOfBoundsException ie)
{System.out.println("ArrayIndexOutOfBoundsException");}
FINALLY
The code in a finally block is always executed before the method ends, regardless of whether any exceptions
are thrown in the try block. finally must always follow a try block. Else it will give a compile time error. catch
block is not mandatory. finally block is used to put cleanup code such as closing a file, closing connection etc.
For each try block there can be zero or more catch blocks but only one finally block.
The finally block will not be executed if program exits either by calling System.exit() or by causing a fatal error
that causes the process to abort. If a try block calls the System.exit() method and the finally block calls the
same method, the exit() method in the finally block executes. The try blocks exit() method call is abandoned.
THROWS
The other way to handle an exception is using the throws clause. If you decide that you cant handle the
exception properly, then the exception can be declared at the method header using the throws keyword
followed by the class name of the exception. When you call a method that throws an exception, you must
either throw the exception or catch it.
Add the throws clause to the method to pass the error up to the next level. We use this clause when we know
that a particular exception may occur and we cannot handle or do not want to handle.
N.B.: If our method is not handling the exception and declares that it is throwing the Exception and even the
method which is calling our method also not interested in handling the exception and throws the exception
then JRE will catch that Exception.
Example:
import java.util.*;
import java.io.*;
class Exception_4
{
public static void main(String ar[]) throws FileNotFoundException
{
String name;
Scanner ob = new Scanner(new FileReader(textFile.txt));
while(ob.hasNext())
{
if(ob.hasNextInt())
{
age = ob.nextInt();
System.out.println(age);
}
else if(ob.hasNext())
{
name = ob.next();
System.out.println(name);
}
}
ob.close();
}
}
THROW
A program can explicitly throw an exception using the throw statement. The general form of the throw
statement is as follows:
throw <Exception reference>;
The Exception reference must be of type Throwable class or one of its subclasses. A details message can be
passed to the constructor when the exception object is created.
throw new ArithmeticException(Division by zero not allowed);
Example:
class Exception_5
{
public static void main(String ar[])
{
try
{
int result = division(100,10);
result = division(100,0);
}
catch(ArithmeticException e)
{
System.out.println("Exception: "+e.getMessage());
}
}
static int division(int divisor, int dividend)
{
int quotient = 0;
try
{
if(dividend == 0)
{
throw new ArithmeticException("Division by zero not allowed");
}
quotient = divisor/ dividend;
}
finally
{
System.out.println(quotient);
}
return quotient;
}
}
OUTPUT:
10
0
Exception: Division by zero not allowed