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) { Sys...