Java Try-Catch Block


In Java, the try-catch block is used to handle exceptions. Exceptions are errors that occur at runtime and can cause a program to terminate abruptly. By using the try-catch block, you can handle these exceptions and provide a more graceful way to handle errors. Here’s an example of a try-catch block:

try {
    // code that may throw an exception
} catch (Exception e) {
    // code to handle the exception
}

In this example, the try block contains code that may throw an exception. If an exception is thrown, the code in the catch block will be executed. The catch block takes an argument of type Exception, which is the type of exception that will be caught. You can replace Exception with a more specific type of exception to catch only that type of exception.

Here’s an example of a try-catch block that catches a NumberFormatException:

String s = "abc";

try {
    int i = Integer.parseInt(s);
} catch (NumberFormatException e) {
    System.out.println("Invalid number format");
}

In this example, the parseInt method is called on a string that cannot be converted to an integer. This causes a NumberFormatException to be thrown. The try-catch block catches the exception and prints a message indicating that the number format is invalid.

In addition to the catch block, you can also include a finally block in a try-catch block. The finally block contains code that is guaranteed to be executed, regardless of whether an exception is thrown or not. Here’s an example:

try {
    // code that may throw an exception
} catch (Exception e) {
    // code to handle the exception
} finally {
    // code that is always executed
}

In this example, the finally block contains code that will be executed regardless of whether an exception is thrown or not.

By using try-catch blocks in your code, you can handle exceptions in a graceful and controlled manner. This allows your program to recover from errors and continue running, rather than terminating abruptly.

A quick recap of Java