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
-
Java checks each
catchblock in order. -
Only the first matching catch block executes.
-
More specific exceptions should come before general ones.
📘 Example 1: Multiple Exception Types
Output:
-
Once
ArithmeticExceptionis caught, the rest are skipped.
📘 Example 2: Using Exception as the Last Catch
-
The
Exceptioncatch block should always be last, because it's a superclass of most other exceptions.
⚠️ Common Mistake: Putting Exception First
You will get a compile-time error because the specific exception (
ArithmeticException) is already caught by the more general one (Exception).
✅ Summary
-
Multiple
catchblocks 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
Post a Comment