exception

Java Exception Handling

Java Exception Handling

Exception handling is a mechanism to handle runtime errors, allowing the program to continue its execution without abrupt termination. Java provides try, catch, and finally blocks to handle exceptions.

Try and Catch Block

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

The try block is used to write code that might throw an exception. The catch block catches the exception and handles it. In this example, dividing by zero throws an ArithmeticException, which is caught and handled.

Finally Block

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("This block always runs");
        }
    }
}
    

The finally block is always executed, regardless of whether an exception is thrown or not. It is typically used to close resources like files or network connections.