How to use multiple catch block in java, with examples
In Java, you can use multiple catch blocks to handle different types of exceptions that may be thrown by a try block. Each catch block can handle a specific type of exception, allowing you to provide tailored error handling for different scenarios.
try {
// Code that may throw exceptions
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} catch (ExceptionType3 e3) {
// Handle ExceptionType3
} finally {
// Optional block that executes regardless of whether an exception was thrown
}
Here’s a simple example demonstrating the use of multiple catch blocks:
import java.util.Scanner;
public class MultipleCatchExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int number = scanner.nextInt(); // This may throw InputMismatchException
// This may throw ArithmeticException if number is 0
int result = 100 / number;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Please enter a valid integer.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
scanner.close(); // Close the scanner resource
System.out.println("Scanner closed.");
}
}
}
Try Block: The code that may throw exceptions is placed inside the try
block. In this example, we are reading an integer from the user and then dividing 100 by that integer.
Catch Blocks:
catch
block handles ArithmeticException
, which occurs if the user enters 0
(division by zero).catch
block handles InputMismatchException
, which occurs if the user enters a non-integer value.catch
block is a generic catch for any other exceptions that might occur.Finally Block: The finally
block is optional and will execute regardless of whether an exception was thrown or not. It is often used for cleanup activities, such as closing resources.
|
) operator (Java 7 and later):catch (ArithmeticException | InputMismatchException e) {
System.out.println("Error: Invalid input.");
}
This allows you to handle multiple exception types in a single block, which can simplify your code if the handling logic is the same.