Java try...catch

ww‮.w‬theitroad.com

In Java, the try-catch block is a mechanism for handling exceptions that occur during program execution. The try block contains the code that may throw an exception, while the catch block contains the code that handles the exception.

The syntax for a try-catch block is as follows:

try {
    // code that may throw an exception
} catch (ExceptionType1 ex1) {
    // code to handle exception of type ExceptionType1
} catch (ExceptionType2 ex2) {
    // code to handle exception of type ExceptionType2
} finally {
    // code to execute whether an exception was thrown or not
}

In this example, the try block contains the code that may throw an exception. The catch block contains the code that will be executed if an exception of type ExceptionType1 or ExceptionType2 is thrown. If an exception is thrown that is not caught by any of the catch blocks, it is propagated up the call stack.

The finally block is optional and contains code that will be executed regardless of whether an exception was thrown or not. This is useful for performing cleanup operations, such as closing files or releasing resources.

Here's an example of a try-catch block in action:

try {
    int result = 10 / 0; // divide by zero to throw ArithmeticException
} catch (ArithmeticException ex) {
    System.out.println("Error: " + ex.getMessage());
} finally {
    System.out.println("This code will always execute.");
}

In this example, an ArithmeticException is thrown because we are attempting to divide by zero. The catch block handles this exception by printing an error message. The finally block prints a message indicating that it will always execute.