Friday, 25 September 2020

Java Program to handle divide by zero exception

 Exception Handling

Exceptions are the run-time errors that can be caught and handled by the programmers to avoid termination of program execution. The statements which may cause a run-time error are written inside the try block and the statements which are to be executed when an error is encountered are placed inside the catch block. A try block can be followed by more than one catch block or a finally block. The statements inside the finally block will be executed either if there is an error or no error in the program. The following program explains how to write try and catch blocks to handle exceptions. If more than one catch block follows the try block, then the catch blocks must be placed in the reverse order of the order in which the exceptions are inherited. All the exceptions both pre-defined and user-defined are the derived class of the base class Exception.


Program

import java.io.*;

class TryCatch
{
  public static void main(String[] arg)
  {
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
    int a,b,c;
    try
    {
        System.out.println("Enter two numbers");
        a=Integer.parseInt(x.readLine());
        b=Integer.parseInt(x.readLine());
        c=a/b;
        System.out.println("Division result = "+c);
    }
    catch(NumberFormatException e)
    {
        System.out.println("Input must be an Integer");
    }
    catch(ArithmeticException e)
    {
        System.out.println("Divide by zero error "+e);
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
  }
}


OUTPUT

D:\Java\19csc>java TryCatch
Enter two numbers
10
2
Division result = 5

D:\Java\19csc>java TryCatch
Enter two numbers
10
0
Divide by zero error java.lang.ArithmeticException: / by zero

D:\Java\19csc>java TryCatch
Enter two numbers
a
Input must be an Integer java.lang.NumberFormatException: a