Exception Handling in Java

Exception handling is a mechanism to handle runtime errors gracefully. In Java, exceptions are objects that are thrown at runtime when an abnormal condition occurs in the program. Java provides a robust exception handling mechanism through try-catch blocks.

Try-Catch Block

A try-catch block is used to handle exceptions. The code that might throw an exception is enclosed within the try block, and the code that handles the exception is written in the catch block. Below is an example of using a try-catch block in Java:


try {
    // Code that might throw an exception
    int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
    // Handling the exception
    System.out.println("An error occurred: " + e.getMessage());
}

Multiple Catch Blocks

Java allows multiple catch blocks to handle different types of exceptions separately. Each catch block can handle a specific type of exception. Below is an example demonstrating multiple catch blocks in Java:


try {
    // Code that might throw an exception
    String str = null;
    System.out.println(str.length()); // This will throw a NullPointerException
} catch (ArithmeticException e) {
    // Handling arithmetic exception
    System.out.println("ArithmeticException occurred: " + e.getMessage());
} catch (NullPointerException e) {
    // Handling null pointer exception
    System.out.println("NullPointerException occurred: " + e.getMessage());
}

Finally Block

The finally block is used to execute code that should always run, whether an exception is thrown or not. It is typically used to release resources such as file handles or database connections. Below is an example illustrating the use of a finally block in Java:


try {
    // Code that might throw an exception
    System.out.println("Try block executed");
} catch (Exception e) {
    // Handling the exception
    System.out.println("An error occurred: " + e.getMessage());
} finally {
    // Code that always runs
    System.out.println("Finally block executed");
}

Throwing Exceptions

In Java, you can manually throw exceptions using the throw keyword. This allows you to create custom exceptions or throw predefined exceptions. Below is an example demonstrating throwing exceptions in Java:


public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            // Code that might throw an exception
            throw new IllegalArgumentException("Custom exception message");
        } catch (IllegalArgumentException e) {
            // Handling the exception
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}