🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Java Notes
Topic #86

Java Multiple Exceptions


Multiple Exceptions

Sometimes, different errors (exceptions) can happen in the same try block. You can handle them with multiple catch blocks.


One try, Many catch

You can add more than one catch block, and Java will run the first one that matches the thrown exception type:

Example

public class Main {
  public static void main(String[] args) {
    try {
      int[] numbers = {1, 2, 3};
      System.out.println(numbers[10]);  // ArrayIndexOutOfBoundsException
      int result = 10 / 0;              // ArithmeticException
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println("Array index does not exist.");
    }
    catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero.");
    }
    catch (Exception e) {
      System.out.println("Something else went wrong.");
    }
  }
}

Explanation: Only the first exception (ArrayIndexOutOfBoundsException) is thrown, so only the first matching catch runs.


Order Matters

You should always put more specific exceptions first, and general ones later. Otherwise, the general catch will grab the error and the specific ones will never run:

Example (bad order)

try {
  int result = 10 / 0;
}
catch (Exception e) {
  System.out.println("General error.");
}
catch (ArithmeticException e) {
  // This will never be reached
  System.out.println("Divide by zero.");
}

Tip: Always put Exception (the general one) at the end.


Multi-Catch

Since Java 7, you can catch multiple exceptions in one catch block using the | symbol. This is useful when different exceptions should be handled in the same way, so you don't have to repeat code:

Example

try {
  int result = 10 / 0;
  int[] numbers = {1, 2, 3};
  System.out.println(numbers[10]);
}
catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
  System.out.println("Math error or array error occurred.");
}

Want to go beyond the notes?

Join CodingNow 2.0's Java course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Java Multiple Exceptions – FAQs

Quick answers about learning Java Multiple Exceptions in Java.

This free note from CodingNow 2.0 explains Java Multiple Exceptions in Java — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Java topic on CodingNow 2.0, including Java Multiple Exceptions, is 100% free with no signup required.
With focused practice, most students grasp Java Multiple Exceptions in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now