Multiple catch block with single try block

Q. Write a Java program to illustrate multiple catch block using command line argument.

Answer:

The catch block is used to handle the exception which is raised in try block. A single try block may contain more than one catch block. Below example shows how to use to multiple catch block.

Check_Exception.java

class Check_Exception
{
        public static void main(String[] args)
        {
                try
                {
                        int a = Integer.parseInt(args[0]);
                        int b = Integer.parseInt(args[1]);
                        int c = a / b;
                        System.out.println("Result: "+c);
                }
                catch (ArithmeticException ae)
                {
                        System.out.println("Enter second number except zero.");
                }
                catch(ArrayIndexOutOfBoundsException ai)
                {
                        System.out.println("Both numbers are required.");
                }
                catch(NumberFormatException ne)
                {
                        System.out.println("Enter only integer value.");
                }
                finally
                {
                        System.out.println("Finally Block");
                }
        }
}


Output:

multiple catch single try