Tuesday, December 23, 2014

Java: Exception Handling

Java Exception-

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 means at some point, the exception is caught and processed.

Handling Exceptions-

There are two ways for handling exception-
First catch the exception and take corrective action
or
Throws exception to the calling method which will forces the calling method to handle it

Method#1- Catch the exception and take corrective action

public class DivideExceptionHandle {

    public static void main(String[] args) {
       
        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Please enter first number(numerator): ");
        int numerator = inputDevice.nextInt();
        System.out.print("Please enter second number(denominator): ");
        int denominator = inputDevice.nextInt();        
        new DivideExceptionHandle().doDivide(numerator, denominator);      
    }
   
    public void doDivide(int a, int b){
        try{  
            float result = a/b;  
            System.out.println("Division result of "+ a +"/"+b +"= " +result);  
        }catch(ArithmeticException e){  
            System.out.println("Exception Condition Program is ending ");  
        }
    }
}

Method# 2- Throws exception to the calling method which will forces the calling method to handle it

public class DivideExceptionThrows {

    public static void main(String[] args){
       
        Scanner inputDevice = new Scanner(System.in);
        System.out.print("Please enter first number(numerator): ");
        int numerator = inputDevice.nextInt();
        System.out.print("Please enter second number(denominator): ");
        int denominator = inputDevice.nextInt();        
        try {  
            new DivideExceptionThrows().doDivide(numerator, denominator);  
        } catch (Exception e) {  
            System.out.println("Exception Condition Program is ending ");  
        }      
    }
   
    public void doDivide(int a, int b) throws Exception{
            float result = a/b;
            System.out.println("Division result of "+ a +"/"+b +"= " +result);
    }
}
}

Use of Finally block


When you have actions you must perform at the end of a try...catch sequence, you can use a finally block.

The code within a finally block executes regardless of whether the preceding try block identifies an Exception.

Usually, you use a finally block to perform cleanup tasks e.g. In application where database connection, files are being operated, we need to take of closing those resources in exceptional condition as well as normal condition

Following example shows how finally works-

import java.util.*;

class Test
    {
    public static void main(String[] args) throws Exception
        {
       
        try
            {
            BadMethod();
           System.out.println("A");
        }
        catch(ArithmeticException e)
        {
            System.out.println("Test");
        }
        catch(Exception e)
            {
            System.out.println("Bad Input");
        }
        finally
            {
            System.out.println("C");
        }
        System.out.println("D");
    }
    public static void BadMethod()
        {}
}

Output- 
A
C
D

Nested Try-Catch Block

We can always catch some exception specifically which can occur and use java run time system to handle the other exceptions. But we need to make sure that super class Exception should come in the last catch else you will get a compile time error e.g. Following code will throw error


import java.util.*;

class Test
    {
    public static void main(String[] args) throws Exception
        {
        int a=5, b=0;
        try
            {
               System.out.println(a/b);     
        }
        
        catch(Exception e)
            {
            System.out.println("Bad Input");
        }
         catch(ArithmeticException e)
        {
            System.out.println("Test");
        }
    }
}

error: exception ArithmeticException has already been caught

Following is the fix for above code-

import java.util.*;

class Test
    {
    public static void main(String[] args) throws Exception
        {
        int a=5, b=0;
        try
            {
           System.out.println(a/b);
        }
        catch(ArithmeticException e)
        {
            System.out.println("Test");
        }
        catch(Exception e)
            {
            System.out.println("Bad Input");
        }      
    }

}

Output- Test

No comments:

Post a Comment