Exception Handling

Effectively manage exceptions in your Java code, ensuring robust error handling and graceful recovery when issues arise.

Exception Handling
Photo by Nathan Dumlao / Unsplash

Effectively manage exceptions in your Java code, ensuring robust error handling and graceful recovery when issues arise.

public class ExceptionHandling {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero");
        }
    }

    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero");
        }
        return a / b;
    }
}