Skip to content
Justice Tech School

Custom Exceptions

Extend Exception for your own error types.

Example
public class Main {
  static class BadAge extends Exception { BadAge(String m) { super(m); } }
  static void check(int a) throws BadAge { if (a < 0) throw new BadAge("negative"); }
  public static void main(String[] args) {
    try { check(-1); } catch (BadAge e) { System.out.println("bad: " + e.getMessage()); }
  }
}

Result

bad: negative

Exercise

Your own exception.

class E  Exception

Quiz Test

What do custom exceptions extend?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.