fbpx

What is the purpose of the "try-catch-finally" block in Java? Provide an example.

The "try-catch-finally" block in Java is used for exception handling. The "try" block contains the code that might throw an exception, the "catch" block catches and handles the exception, and the "finally" block contains code that will be executed regardless of whether an exception occurs or not.

try {
    // Code that might throw an exception
    int result = 10 / 0; // Example of an exception
} catch (ArithmeticException e) {
    // Handle the exception
    System.out.println("An arithmetic exception occurred: " + e.getMessage());
} finally {
    // Code that will be executed regardless of whether an exception occurs or not
    System.out.println("Finally block executed.");
}

 

# Dream job to realty