Java Multiple Exceptions

⚠️ Java Multiple Exceptions

In Java, a single try block can throw more than one type of exception. To handle this, we can use:

  1. Multiple catch blocks

  2. Single catch block using multi-catch (Java 7+)

  3. Catching the parent exception class


 1. Multiple catch Blocks

Different exceptions can be handled separately.

Example:

public class MultipleExceptionsExample {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]); // ❌ Array index issue
int result = 10 / 0; // ❌ Arithmetic exception
System.out.println(result);} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Error: Array index out of range!”);
} catch (ArithmeticException e) {
System.out.println(“Error: Cannot divide by zero!”);
} catch (Exception e) {
System.out.println(“General Exception: “ + e.getMessage());
}
}
}

🔍 Rule: Order of catch Matters

More specific exceptions must come before general exceptions.
Otherwise, the compiler shows an error.

❌ Wrong:

try { ... }
catch (Exception e) { ... }
catch (ArithmeticException e) { ... } // ERROR!

Because Exception already handles everything.


 2. Multi-Catch (Java 7+)

To avoid writing many catch blocks, we can combine exceptions using |:

public class MultiCatchExample {
public static void main(String[] args) {
try {
int num = 10 / 0;
} catch (ArithmeticException | NullPointerException e) {
System.out.println("Either Arithmetic or Null Pointer Exception occurred!");
}
}
}

⚠️ Multi-Catch Rule

You cannot combine exceptions with parent-child relationship.

Example:

catch (Exception | ArithmeticException e) { }

❌ Invalid — because ArithmeticException is already included in Exception.


 3. Catching Parent Exception

Instead of multiple catches, you can catch the superclass Exception.

public class ParentCatchExample {
public static void main(String[] args) {
try {
String text = null;
System.out.println(text.length()); // NullPointerException
} catch (Exception e) {
System.out.println(“An error occurred: “ + e);
}
}
}

🧠 Summary Table

Method Catch Style Best Use Case
Multiple catch blocks Specific exceptions Precise control
Multi-catch ( ) One block handles multiple exception types
Single parent catch Exception e General handling/logging

Real-Life Example

public class RealLifeMultiException {
public static void main(String[] args) {
try {
String[] users = {"Amit", "Raj", "Sara"};
System.out.println(users[5]); // ArrayIndexOutOfBounds
int age = Integer.parseInt(“abc”); // NumberFormatException} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(“Invalid array access!”);
} catch (NumberFormatException e) {
System.out.println(“Invalid number format!”);
}
}
}

You may also like...