Using Multiple Catch Blocks in Java with Examples

Respondido usando: GPT-4o-mini porJava Q&A Hub

Pergunta:

How to use multiple catch block in java, with examples

Resposta:

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.

Syntax

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
}

Example

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.");
        }
    }
}

Explanation

  1. 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.

  2. Catch Blocks:

    • The first catch block handles ArithmeticException, which occurs if the user enters 0 (division by zero).
    • The second catch block handles InputMismatchException, which occurs if the user enters a non-integer value.
    • The third catch block is a generic catch for any other exceptions that might occur.
  3. 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.

Notes

  • The order of catch blocks matters. More specific exceptions should be caught before more general exceptions. If you place a general exception catch block before a specific one, the specific one will never be reached.
  • You can also catch multiple exceptions in a single catch block using the pipe (|) 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.