8 Exception Handling






Whenever an Error is encountered while executing a program, an Exception is said to have occurred.  An exception can also be termed as a special type of error.  It arises at run time in a code sequence, mostly, due to abnormal conditions that occur at the time of running the program.

When an exception occurs, an object, which represents that exception is created and passed to the method where the exception has occurred.  This object contains delailed information about the exceptin, which can be retrieved and processed.  Exceptions can be thrown by run-time environment such as IllegalAccessException or EmptyStackException or it can be manually generated by the code.  Throwable class provided in the language is the super class of Exception Class, which in turn is a super class of the individual exceptions.

Error and Exception handling is used to foresee and identify error conditions and perform processing to take care of their impact.

Exceptions in Java
Java provides an exception handling model that allows us to check for errors where it is relevant to do so.  It implements a catch and throw model of exception handling similar to the one used in C++.  Instead of returning erros from a method using the normal return value or parameter mechanism, java provides en exception handling facility.

Errors and other exceptional conditions are treated as distinct from the normal flow of control in the program, which after all, they are.  When an error occurs, an exception is thrown.  Exceptions climb the chain of calls until they are caught or until the program exists.  The catch and throw method of exception handling offers two big advantages:

1)                  An error condition can be dealt with only where it makes sense instead of dealing with it at every level between where it occurs and where it needs to be dealt with.
2)                  Code can be written as if the error message for a particular error, whch we expect to occur, works, when the particular error is caught.

Try and catch
The language support for the catch and throw method of exception handling is the try / catch block.  Following is the Try Block:-
try {
doFileProcessing( );
displayResults( ) ;
}
catch(Exception e){
System.err.println(“Error : “+ e.getMessage( ));
}

Any error that occurred during the execution of doFileProcessing( ) or displayResults( ) would be caught by catch( ) and processed as specified.  If an error occurred duging doFileProcessing( ), the method displayResults( ) would never get called, and the execution would proceed directly to the catch block. 

We can also usemultiple catch( ) blocks together and process various exception types differently.
try {
doFileProcessing( );
displayResults( ) ;
}
catch(LookException e){
handleLookExceptio (e);
}
catch(Exception e){
System.err.println(“Error : “+ e.getMessage( ));
}
in the above case, a LookException would be caught and processed by the first catch and any other type of exception would be handled by the second catch.

The finally Statement
Exceptions can cause control to leave the current method without completing the method’s execution.  If there is a cleanup code such as the code required to close files at the end of the method, it will never get called.  To deal with this, java provides finally block. The Finally block can be use in conjunction with a try block.  Basically it ensures that if an exception has occurred, any cleanup work, which is necessary, is taken  care of.  This is because the code in a finally block is guaranteed to run whether an exception occurs or not.  For example:-
try {
doSomething( );
}
finally
{
CleanUp( ) ;
}
if the doSomeThing( ) throws an exception, the cleanup ( ) method will still be called and then the exception will continue to call other chain.  If an exception is not thrown, the CleanUp( ) is called and the execution will proceed after the finally block.

Different types of Exceptions our code can throw are as follows:-

Ø  Runtime Exception
o   ArithmethicException
o   IllegalArgumentException
o   ArrayIndexOutOfBoundsException
o   NullPointerException
o   SecurityException
o   NoSuchElementException
Ø  ClassNotFoundException
Ø  AWTException

Ø  DataFormatException
Ø  SQLException
Ø  IOException
o   UnKnownHostException
o   SocketException
o   EOFException
o   MalformedURLExeption
o   FileNotFoundException
Ø  IllegalAccessException
Ø  NoSuchMethodException

Purpose of Exception Handling
Whenever an exception occurs, in the program in which proper exception handling mechanism is not provided, the program aborts, leaving all the resources previously allocated in the same state.  This can lead to resource leak.  To avoid this, in a proper exception handling mechanism we can return all the resources which are previously allocated by the system, to the sysem.  So each exception must be handled separately by keeping in mind when they might possibly occur.

Try Block
The try block consists of a set of executable statements that can possibly throw exception while executing them.  A method, which may throw an exception can also be included in the try block.  A try block can be followed by one or more catch blocks where exception thrown in the try block is caught.  On the other hand, a try( ) block may not be followed by a catch ( ) block as follows:
int demo = 0;
try {
System.out.println(20/demo);
}
the statement System.out.println(20/demo); will throw an exception because we are trying to ddivide a number by zero.  The program compilation will be successful, but on execution the program will be terminated.  This because the exception is thrown at run time.

Catch Block
The catch block catches the exceptions thrown in the try block.  Without the try block no catch block can exist.  We can have multiple catch blocks covering different types of exceptions.

Example 1(Exception)
class TryClass{
public static void main(String args[]){
int demo=0;
try{
System.out.println(20/demo);
}
catch(ArithmeticException a){
System.out.println(“Can not Divide Zero “);
}
}
}

In above program we are trying to divide a number by zero which is not a valid arithmetic operation.  Hence, an exception is thrown which is caught in the caught in the catch block provided. 

Throws Clause
In java when an error condition ariases in a program, we send an exception up the call chain by using the throw keyword.  The java exception class implements the Throwable interface and provides some useful features for dealing with exceptions.  It is often useful to create our own exception class for special case exception handling within the program.  This is normally done by creating a subclass of the exception class.  The advantage of the sub-classing the exception class is that, the new exception type can be caught separately from other Throwable types.

Example 2(Throws Exception)
import java.io.*;
public class ThrowsDemo{
public static  void main(String args[])throws IOException,NumberFormatException{
double aimedAmt;
double interest=7.5;
double payment;
int years=0;
double balance=0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
System.out.print("Amout to be expected at the time of retirement ");
aimedAmt=Double.valueOf(br.readLine( )).doubleValue( );
System.out.println(" ");
System.out.print("Your Contribution In each year  ");
payment=Double.valueOf(br.readLine( )).doubleValue( );
System.out.println(" ");
while(balance<aimedAmt){
balance=(balance+payment)*(1+(interest/100));
years++;
}
System.out.println("You Can Retire in "+years+"Years.");
}
}

Throw keyword
Throw keyword is used to indicate that exception has occurred.  The operand of throw is an object of a class, which is derived from class Throwable.

Example 3(Throw Exception)
class ArraySizeException extends NegativeArraySizeException{
ArraySizeException( ){
super("Illegal Array Size ");
}
}
class ThrowDemo{
int size,arr[];

ThrowDemo(int s){
size=s;
try{
checkSize( );
}
catch(ArraySizeException e){
System.out.println(e);
}
}
void checkSize( ) throws ArraySizeException{
if(size<0)
throw new ArraySizeException( );
arr=new int[3];
for(int i=0;i<3;i++)
arr[i]=i+1;
}
public static  void main(String args[])
{
new ThrowDemo(Integer.parseInt(args[0]));
}
}

Finally Block
Finally block is the block in which we find statements which return resources to the system and other statements for printing any message.  Typically, these statements include

Ø  Closing a file
Ø  Closing a resultset(Used in Database programming)
Ø  Closing a connection established with the database

This block is optional but when included is placed after the last catch block of a try( ).  The finally block always executed no matter whether exception is thrown or not.  If in a try block, a return or a breack statement is used, then on executing that statement, the control comes to first statement of the finally block.

The above figure Denotes two possibilities one when not exception, then the control directly execute the finally block.  And in second  situation it catch the error and then passes the control to finally block.

Example 4(Finally)
class FinallyDemo 
{
String name;
int no1,no2;
FinallyDemo(String args[])
{
try
{
name = new String("Leenas Software");
no1= Integer.parseInt(args[0]);
no2= Integer.parseInt(args[1]);
System.out.println(name);
System.out.println("Division Result is "+no1/no2);
}
catch(ArithmeticException i)
{
System.out.println("Can not devide by Zero ");
}
finally{
name = null;
System.out.println("Finally excecuted ");
}
}
public static  void main(String args[])
{
new FinallyDemo(args);
}
}

Practical Examples


Example 1 (ArrayIndexOutOfBoundsException)

public class CatchExp{
public static  void main(String args[])
{
int []arr=new int[10];
try{
arr[11]=10;
}
catch(ArrayIndexOutOfBoundsException e)
{
e = new ArrayIndexOutOfBoundsException(" \t\tHello Notice the Length of the Array");
throw(e);
}
     }
}

Example 2 (Divide By Zero Exception)
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class divZero extends Applet implements ActionListener
{
Label l1,l2;
TextField tf1,tf2;
int num1,num2;
double result;
public void init( )
{
l1= new Label("Enter Numerator :");
tf1 = new TextField(10);
l2= new Label("Enter Denominator and press Enter :");
tf2 = new TextField(10);
add(l1);
add(l2);
add(tf1);
add(tf2);
tf2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
num1=Integer.parseInt(tf1.getText());
tf1.setText(" ");
num2=Integer.parseInt(tf2.getText());
tf2.setText(" ");
try
{
result =quotient(num1,num2);
showStatus(num1 +" / " + num2 + " = " +Double.toString(result));
}

catch(ArithmeticException e){
showStatus (e.toString());
}
}
public double quotient(int numerator, int denominator)throws ArithmeticException
{
if(denominator ==0)
throw new ArithmeticException();
return(double)numerator/denominator;
}
}

Example 3 (Using the  Exception)

class UseExp{
public static void main(String args[]){
try{
throwException( );
}
catch(Exception e){
System.err.println("Exception Handled in Main ");
}
doesNotThrowException( );
}
public static void throwException() throws Exception
{
try{
System.out.println("Method throwsException");
throw new Exception( );
}
catch(Exception e){
System.err.println("Exception handled in Method throws Exception");
throw e;
}
finally{
System.err.println("Finally is always Executed");
}
}
public static void doesNotThrowException( ){
try{
System.out.println("Method Does not Throw Exception ");
}
catch(Exception e){
System.out.println(e.toString( ));
}
finally{
System.out.println("Finally is always executed");
}
}
}

No comments:

Post a Comment