Multiple Catch Blocks in Java: Rules, Order, and Best Practices
📌 Multiple Catch Blocks in Java (Professional & Beginner-Friendly Explanation)
When a programmer uses a try block followed by multiple catch blocks, Java follows strict rules to avoid ambiguity while handling exceptions.
🔹 Key Rules of Multiple Catch Blocks
1️⃣ No Duplicate Catch Blocks Allowed
Each catch block must handle a different exception type.
❌ Invalid Code (Duplicate Catch):
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
System.out.println("Arithmetic Exception");
}
catch (ArithmeticException e) { // ❌ Duplicate
System.out.println("Duplicate Exception");
}
📌 Reason:
The JVM will be confused about which catch block to execute, resulting in a compile-time error.
2️⃣ Superclass Catch Can Handle Subclass Exceptions
A catch block with a superclass exception can handle all its subclass exceptions.
📌 Example:
try {
int[] arr = new int[5];
arr[10] = 50;
}
catch (Exception e) {
System.out.println("Handled by Exception class");
}
✔ Here, Exception handles ArrayIndexOutOfBoundsException because it is a subclass of Exception.
3️⃣ Order of Catch Blocks Is Very Important
When multiple catch blocks are used:
✅ Subclass exception must come before superclass exception
❌ Wrong Order (Compile-Time Error):
try {
int[] arr = new int[5];
arr[10] = 50;
}
catch (Exception e) { // ❌ Superclass first
System.out.println("Exception");
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error");
}
📌 Reason:
The superclass Exception can already handle the subclass exception, so the subclass catch block becomes unreachable code.
✅ Correct Order (Subclass → Superclass)
try {
int[] arr = new int[5];
arr[10] = 50;
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error");
}
catch (Exception e) {
System.out.println("General Exception");
}
✔ The JVM checks catch blocks top to bottom and executes the first matching block.
🔹 Real-Life Example
📌 ATM Transaction System
try {
int balance = 5000;
int withdraw = 6000;
int result = balance / (balance - withdraw);
}
catch (ArithmeticException e) {
System.out.println("Invalid arithmetic operation");
}
catch (Exception e) {
System.out.println("Something went wrong");
}
✔ Specific issues are handled first
✔ General issues are handled later
📝 Summary Table
Rule Explanation
Duplicate catch. ❌ Not allowed
Superclass catch. Can handle subclass exceptions
Catch order. Subclass first, superclass last
JVM behavior. Executes first matching catch
Comments
Post a Comment