try with multiple catch clauses

In Java, the try block can be followed by multiple catch blocks, allowing you to handle different types of exceptions separately. This is helpful when different error conditions need different responses.


✅ Syntax of try with Multiple catch Blocks


try { // Code that might throw multiple exceptions } catch (ExceptionType1 e1) { // Handle ExceptionType1 } catch (ExceptionType2 e2) { // Handle ExceptionType2 } catch (ExceptionType3 e3) { // Handle ExceptionType3 }
  • Java checks each catch block in order.

  • Only the first matching catch block executes.

  • More specific exceptions should come before general ones.


📘 Example 1: Multiple Exception Types


public class MultipleCatchExample { public static void main(String[] args) { try { int[] arr = {1, 2, 3}; int result = 10 / 0; // Throws ArithmeticException System.out.println(arr[5]); // Would throw ArrayIndexOutOfBoundsException if reached } catch (ArithmeticException ae) { System.out.println("Arithmetic Error: " + ae.getMessage()); } catch (ArrayIndexOutOfBoundsException aioobe) { System.out.println("Array Index Error: " + aioobe.getMessage()); } catch (Exception e) { System.out.println("General Exception: " + e.getMessage()); } } }

Output:


Arithmetic Error: / by zero
  • Once ArithmeticException is caught, the rest are skipped.


📘 Example 2: Using Exception as the Last Catch


try { String text = null; System.out.println(text.length()); // NullPointerException } catch (NullPointerException ne) { System.out.println("Null value error!"); } catch (Exception e) { System.out.println("Some other error occurred."); }
  • The Exception catch block should always be last, because it's a superclass of most other exceptions.


⚠️ Common Mistake: Putting Exception First

try {
// risky code } catch (Exception e) { // This catches everything } catch (ArithmeticException ae) { // ❌ Compile-time error: unreachable catch block }

You will get a compile-time error because the specific exception (ArithmeticException) is already caught by the more general one (Exception).


✅ Summary

  • Multiple catch blocks allow fine-grained handling of exceptions.

  • Place specific exceptions before general ones.

  • The JVM checks catch blocks top to bottom, and executes the first match.

  • Helps in writing clean and robust error-handling code.

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism