AnyCompiler

Exception Handling

A try block runs code that might throw an exception; a matching catch block handles it if it does. ArithmeticException here is an unchecked exception — the compiler doesn't require you to handle it, though it's good practice to.

public class Main {
    static int divide(int a, int b) {
        return a / b;
    }

    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 2));
            System.out.println(divide(10, 0));
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Output
5
Error: / by zero

Checked exceptions: what a real compile error looks like

Java has a second category with no equivalent in the other languages on this site: checked exceptions. A method that can throw one, like IOException here, has to either catch it or declare throws IOException in its own signature — if it does neither, the code simply doesn't compile. This is genuinely what javac reports — captured from a real run, not written to look plausible:

import java.io.IOException;

public class Main {
    static void risky() throws IOException {
        throw new IOException("something went wrong");
    }

    public static void main(String[] args) {
        risky();
    }
}
Output
Main.java:9: error: unreported exception IOException; must be caught or declared to be thrown
        risky();
             ^
1 error

risky() declares throws IOException, which is the method's part of the deal — but main() calls risky() without catching that exception or declaring its own throws, so the compiler refuses to build. Adding try/catch around the call, or throws IOException to main's own signature, would fix it either way.

Next: generics — writing one class or method that works across many types, with the compiler still checking type safety.

Practice exercise

Write a method safeDivide(int a, int b) that returns a / b, but catches ArithmeticException and returns 0 if b is 0. Call it with (10, 0) and print the result.