![]() |
VOOZH | about |
In Java, exception handling allows a program to deal with runtime errors gracefully. Sometimes, a single try block can throw different types of exceptions, and Java provides two ways to handle such scenarios:
Example: Handling Multiple Exceptions
Arithmetic Exception occurred
try {
// code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 ex) {
// exception handling code
}
Parameters: "ex" -> Exception object
Return Type: catch block does not return any value
Starting from Java 7, Java introduced the multi-catch feature, allowing a single catch block to handle multiple exception types using the pipe (|) operator. This enhancement:
Syntax:
Note: The exception parameter ex is implicitly final in a multi-catch block.
Example:
Exception caught: java.lang.NumberFormatException: For input string: "ABC"
Explanation:
- Multi-catch is allowed only from Java 7 onwards.
- All exception types must be separated using the pipe symbol |.
- Parent and child exceptions cannot be combined in a multi-catch block.
Invalid Example:
try {
int num = Integer.parseInt("XYZ");
} catch (NumberFormatException | Exception ex) {
System.out.println(ex);
}
Explanation: