Learn / Java / Exception Handling

Intermediate 13 min

Exception Handling

try/catch/finally and throwing checked exceptions.

What you will learn

  • Catch NumberFormatException
  • Use finally
  • Throw IllegalArgumentException
java
public static int parsePositive(String raw) {
    try {
        int n = Integer.parseInt(raw);
        if (n <= 0) throw new IllegalArgumentException("must be positive");
        return n;
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("not a number", e);
    }
}

Try it yourself

Write a method that divides two ints and returns 0 on divide-by-zero.