Vous êtes sur la page 1sur 10

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;

System.out.print("Enter numerator >> ");


numerator = input.nextInt();
System.out.print("Enter denominator >> ");
denominator = input.nextInt();
result = numerator / denominator;
System.out.println(numerator + " / " + denominator + " = " + 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.

Table 1 : Most commonly encountered exceptions and their explanation

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;

System.out.print("Enter numerator >> ");


numerator = input.nextInt();
System.out.print("Enter denominator >> ");
denominator = input.nextInt();
try {
result = numerator / denominator;
System.out.println(numerator + " / " + denominator + " = " + result);
}
catch(ArithmeticException e)
{
System.out.println("Exception");
}
}
}

Enter numerator >> 5


Enter denominator >> 0
Exception

DISPLAYING A DESCRIPTION OF AN EXCEPTION


Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a
description of the exception. You can display this description 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)
{
System.out.println("Exception: "+e);
}

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.

MULTIPLE CATCH BLOCK


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.

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

NESTED TRY STATEMENTS


Sometime a situation may arise where a part of a block may cause an error and the entire block itself may
cause another error. In such cases exception handlers have to be nested.
The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a
try statement is entered, the context of that exception is pushed on the stack. If an inner try statement does
not have a catch handler for a particular exception, the stack is unwound and the next try statements catch
handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all the
nested try statements are exhausted. If no catch statement matches, then the Java run-time system will
handle the exception.

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");}

static void check(int a)


{
try{
int b = 30/a;
}
catch(ArithmeticException ae)
{System.out.println("ArithmeticException");}
}
}
OUTPUT:
ArrayIndexOutOfBoundsException / ArithmeticException

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.

Program incase exception does not occur:


class Exception_3
{
public static void main(String ar[])
{
try
{
int a = 9/3;
System.out.println(a);
}
catch(Exception e)
{ System.out.println(e);}
finally
{ System.out.println(Execute finally);}
System.out.println(Rest);
}
}
OUTPUT:
3
Execute finally
Rest

Program incase exception occur but not handled:


class Exception_3
{
public static void main(String ar[])
{
try
{
int a = 9/0;
System.out.println(a);
}
catch(ArrayIndexOutOfBoundsException e)
{ System.out.println(e);}
finally
{ System.out.println(Execute finally);}
System.out.println(Rest);
}
}
OUTPUT:
Execute finally
Exception in thread main java.lang.ArithmeticException: / by zero

Program incase exception occur and handled:


class Exception_3
{
public static void main(String ar[])
{
try
{
int a = 9/0;
System.out.println(a);
}
catch(ArithmeticException e)
{ System.out.println(Arithmetic Exception: +e);}
finally
{ System.out.println(Execute finally);}
System.out.println(Rest);
}
}
OUTPUT:
Arithmetic Exception: java.lang.ArithmeticException: / by zero
Execute finally
Rest

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);

A thrown Exception can be caught by a catch block.

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

DIFFERENCE BETWEEN THROW AND THROWS


Whenever we want to force an exception then we use throw keyword. It can also pass a custom message to
our exception handling module i.e. the message which we want to be printed. For instance in the above
example we have used
throw new ArithmeticException("Division by zero not allowed");
Whereas when we know that a particular exception may be thrown or to pass a possible exception then we
use throws keyword. Point to note here is that the Java compiler very well knows about the exceptions thrown
by some methods so it insists us to handle them. We can also use throws clause on the method instead of try
and catch exception handler.

USER DEFINED EXCEPTION


Java provides over 40 categories of Exceptions that you can use in your programs. However, Javas creators
could not predict every condition that might be an Exception in your applications. For example, an employee
number must not exceed three digits or an outside party should not access your e-mail account. Of course,
you can handle these potential error situations with if statements, but Java also allows you to create your
own Exceptions. To create your own throwable Exception, you must extend a subclass of Throwable. You can
extend any existing Exception subclass, such as ArithmeticException or NullPointerException, but usually
you want to inherit directly from Exception. When you create an Exception subclass, its conventional to end
its name with Exception.
For example, the following example shows a HighBalanceException class. Its constructor contains a single
statement that passes a description of an error to the parent Exception constructor. This String would be
retrieved if you called the HighBalanceException object or the getMessage() method with a
HighBalanceException object.

public class HighBalanceException extends Exception


{
public HighBalanceException()
{
super("Customer balance is high");
}
public HighBalanceException(String atr)
{
super(str);
}

public class CustomerAccount


{
private int acctNum;
private double balance;
public static double HIGH_CREDIT_LIMIT = 20000.00;
public CustomerAccount(int num, double bal) throws HighBalanceException
{
acctNum = num;
balance = bal;
if(balance > HIGH_CREDIT_LIMIT)
throw(new HighBalanceException());
if(balance == HIGH_CREDIT_LIMIT)
throw(new HighBalanceException(Reached your limit));

public static void main(String ar[])


{
try{
CustomerAccount ob = new CustomerAccount(30,80000);
}
catch(HighBalanceException e)
{System.out.println("Exception: "+e);}
}
}
OUTPUT:
Exception: HighBalanceException: Customer balance is high

Vous aimerez peut-être aussi