BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to Catch multiple exceptions

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In the previous tutorial, I have covered how to handle exceptions using try-catch blocks. In this guide, we will see how to handle multiple exceptions and how to write them in a correct order so that user gets a meaningful message for each type of exception.

Catching multiple exceptions

Lets take an example to understand how to handle multiple exceptions.

class Example{
   public static void main(String args[]){
      try{
         int arr[]=new int[7];
         arr[4]=30/0;
         System.out.println("Last Statement of try block");
      }
      catch(ArithmeticException e){
         System.out.println("You should not divide a number by zero");
      }
      catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Accessing array elements outside of the limit");
      }
      catch(Exception e){
         System.out.println("Some Other Exception");
      }
      System.out.println("Out of the try-catch block");
   }
}

Output:

You should not divide a number by zero
Out of the try-catch block

In the above example, the first catch block got executed because the code we have written in try block throws ArithmeticException (because we divided the number by zero).

Now lets change the code a little bit and see the change in output:

class Example{
   public static void main(String args[]){
      try{
         int arr[]=new int[7];
         arr[10]=10/5;
         System.out.println("Last Statement of try block");
      }
      catch(ArithmeticException e){
         System.out.println("You should not divide a number by zero");
      }
      catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Accessing array elements outside of the limit");
      }
      catch(Exception e){
         System.out.println("Some Other Exception");
      }
      System.out.println("Out of the try-catch block");
   }
}

Output:

Accessing array elements outside of the limit
Out of the try-catch block

In this case, the second catch block got executed because the code throws ArrayIndexOutOfBoundsException. We are trying to access the 11th element of array in above program but the array size is only 7.

What did we observe from the above two examples?
1. It is clear that when an exception occurs, the specific catch block (that declares that exception) executes. This is why in first example first block executed and in second example second catch.
2. Although I have not shown you above, but if an exception occurs in above code which is not Arithmetic and ArrayIndexOutOfBounds then the last generic catch handler would execute.

Lets change the code again and see the output:

class Example{
   public static void main(String args[]){
      try{
         int arr[]=new int[7];
         arr[10]=10/5;
         System.out.println("Last Statement of try block");
      }
      catch(Exception e){
         System.out.println("Some Other Exception");
      }
      catch(ArithmeticException e){
         System.out.println("You should not divide a number by zero");
      }
      catch(ArrayIndexOutOfBoundsException e){
         System.out.println("Accessing array elements outside of the limit");
      }
      System.out.println("Out of the try-catch block");
   }
}

Output:

Compile time error: Exception in thread "main" java.lang.Error: 
Unresolved compilation problems: Unreachable catch block for ArithmeticException.
It is already handled by the catch block for Exception Unreachable catch block 
for ArrayIndexOutOfBoundsException. It is already handled by the catch block for
Exception at Example.main(Example1.java:11)

Why we got this error?
This is because we placed the generic exception catch block at the first place which means that none of the catch blocks placed after this block is reachable. You should always place this block at the end of all other specific exception catch blocks.

❮ PreviousNext ❯

Top Related Articles:

  1. Exception handling in Java with examples
  2. Nested try catch block in Java – Exception handling
  3. Java Exception Handling Examples
  4. How to Compile and Run your First Java Program
  5. What is case Keyword in Java

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Abhishek Bharat Parab says

    March 25, 2017 at 10:50 AM

    Confusion about above example. If ArithmeticException, NullPointerException ArrayIndexOutOfBoundsException exception class are child of RuntimeExecption parent class, and these class is useful to handle runtime exception then why should it be followed by method declaration using throws keyword. since throws keyword is used to handle compile time exception.

    Requesting your assistance for following queries :

    1. If we can handle exceptions(checked/unchecked) using try/catch block, then why should we use throw or throws keyword in program with real time example?

    2. Please tell me a situation where throw or throws keyword has to be used in program. please explain with an example

    3. public void myMethod() throws ArithmeticException {
    int division = 10/0 ;
    step 1: new throw ArithmeticException(“cannot be divided by zero”);

    }

    In this example, If arithmeticException class is used to handle runtime exception, so why do we use it followed by throws keyword in method declaration?
    does step 1 not sufficient to handle “divided by zero” exception?

    I would be awaiting for your response respect to my queries

    Reply
    • raghu says

      May 7, 2017 at 3:44 AM

      keyword throw is used to define pre-defined/user defined exceptions
      throws:
      Actually all the possible exceptions must be handled by using try and catch block if we are not interested to handle checked exceptions atleast we need to make JVM to handle the checked exceptions by using keyword “throws” otherwise jvm will rise compile time error
      throws is not exception handler it is an exception escaper.hence throws are not recommended in the industry programs which leads abnormal termination

      Reply
    • Mithilesh Naik says

      July 23, 2017 at 4:15 PM

      Hi Abhishek,

      Answer o 1) usually you will see operations like these:

      classA.methodA calls classB.methodB which again calls classC.methodC

      class C returns something all the way to class A
      (Only class A is allowed to interact to user)

      in this case if exception occurs in class C then you throw it using
      throw new your-exception //from code
      or add “throws ExpectedException” in method signature of methodC

      MethodC will throw it to methodB this should also have throws declaration. MethodB will throw it to methodA.

      Method A will catch it in a catch block and do corresponding action

      **This answers Q2**

      Answer to 3)
      in case 10/0 you dont need to throw exception explicitly. However say, your operation cannot support divide by 5 (assume). in this case do following

      if (divisor ==5)
      throw OperationNotSupported or throw ArithmeticException

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap