exception

Java Exception Handling

Java Exception Handling

Exception handling in Java is a powerful mechanism to handle runtime errors. It allows you to maintain the normal flow of the application even when unexpected errors occur. Java provides five main keywords for exception handling: try, catch, throw, throws, and finally.

Try and Catch Block

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

The try block contains code that might throw an exception, and the catch block handles that exception if it occurs. In this case, division by zero results in an ArithmeticException.

Throwing an Exception

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            throw new Exception("Custom exception");
        } catch (Exception e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}
    

We can manually throw an exception using the throw keyword. Here, a custom exception is thrown with the message "Custom exception".

Finally Block

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            System.out.println("Trying...");
        } finally {
            System.out.println("This will always execute");
        }
    }
}
    

The finally block is always executed, regardless of whether an exception was thrown or not. It is typically used for cleaning up resources.