11.2 Try and Catch Block

try catch finallyStatements that might generate an exception are placed in a try block.

Each try block needs to be followed by at least one "catch". Each "catch" catches a particular type of exception and is activated only when particular type of exception arises. As a result, we might need several different catch blocks to handle different types of exceptions.

The following example takes two integers from keyboard, divide it and displays result. The program will throw execeptions if user input wrong format data or number is divided by zero.

 

import java.util.*;

public class ExceptionExample
{
   public static void main(String[] args)
   {
      int dividend, divisor, quotient;

      // Create a Scanner object to read input.
      Scanner console = new Scanner(System.in);

      try
      {
         System.out.print("Enter the dividend : ");
         dividend = console.nextInt();

         System.out.print("Enter the divisor : ");
         divisor = console.nextInt();

         quotient = dividend / divisor;
         System.out.println("Quotient = " + quotient);
      }
      catch (ArithmeticException ex)
      { 
         System.out.println("Exception: " + ex.toString());
      }
      catch (InputMismatchException ex)
      { 
         System.out.println("Exception: " + ex.toString());
      }
   }
}

Sample Run # 1

Enter the dividend : 16
Enter the divisor : 5
Quotient = 3
          

Sample Run # 2

Enter the dividend : 15
Enter the divisor : 0
Exception: java.lang.ArithmeticException: / by zero

Sample Run # 3

Enter the dividend : 15
Enter the divisor : z
Exception: java.util.InputMismatchException

 

Note the following about try/catch blocks:

  • If no exception is thrown in a try block, all catch blocks associated
    with the try block are ignored and program execution resumes after the last catch block. (Look at Sample Run#1)
  • If an exception is thrown in a try block, the remaining statements in the try block are ignored. The program searches the catch blocks in the order in which they appear after the try block and looks for an appropriate exception handler. (Look at Sample Run#2 and Sample Run# 3)
  • If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks after this catch block are ignored. (Look at Sample Run#2 and Sample Run# 3)
  • If a catch handler is written to catch superclass exception objects, it can also catch all objects of that class’s subclasses. This enables catch to handle related exceptions polymorphically. For example, Exception objects can also catch objects of RuntimeException objects or ArthimeticException object see fig. of exception heirarchy.

Multi-catch

For handling various types of exceptions, several catch blocks are commonly used. If the bodies of several catch blocks are identical, you can use the multi-catch feature to to perform the same task by using single catch block.

The syntax for a multi-catch is:

catch (ExceptionType1 | ExceptionType2 | ExceptionType3 ex)

The above program could also be re-written using Multi catch


import java.util.*;

/**
 *  This program demonstrates multicatch   
 */

public class MultiCatchExample
{
   public static void main(String[] args)
   {
      int dividend, divisor, quotient;

      // Create a Scanner object to read input.
      Scanner console = new Scanner(System.in);

      try
      {
         System.out.print("Enter the dividend : ");
         dividend = console.nextInt();

         System.out.print("Enter the divisor : ");
         divisor = console.nextInt();

         quotient = dividend / divisor;
         System.out.println("Quotient = " + quotient);
      }
      catch (ArithmeticException | InputMismatchException ex)
      { 
         System.out.println("Exception: " + ex.toString());
      }
   }
}