Codectionary / Developer documentation / Java

Custom Checked Exceptions

Name a domain-specific failure and make callers handle or declare it.

What it is and why to use it

An exception type can explain a failure more clearly than a generic message. A checked exception extends Exception without extending RuntimeException. Java requires code that can throw it to catch it or declare it. This suits a recoverable failure that callers should consciously consider.

How it works

The constructor forwards a message to Exception. requireSeat declares throws NoSeatException and throws an instance when there is no seat. main catches that specific failure and prints a controlled message. Catching an exception does not automatically undo earlier changes; validation before mutation helps avoid inconsistent state.

Common mistakes and limitations

Do not catch Exception and silently continue as though the operation worked. Use unchecked exceptions for programming-contract violations where appropriate rather than making every validation failure checked. Avoid exposing sensitive internal messages to end users.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

class NoSeatException extends Exception { /* constructor */ }

Examples

Custom Checked Exceptions

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  static class NoSeatException extends Exception {
    NoSeatException(String message) { super(message); }
  }
  static void requireSeat(int available) throws NoSeatException {
    if (available <= 0) throw new NoSeatException("No seats available");
  }

  public static void main(String[] args) {
    try {
      requireSeat(0);
      System.out.println("Reserved");
    } catch (NoSeatException error) {
      System.out.println(error.getMessage());
    }
  }
}
  1. requireSeat receives zero, creates a domain-specific exception and throws it.
  2. Control skips Reserved and moves to the matching catch block.
  3. getMessage returns the explanation supplied to the constructor. A booking interface could show a suitable alternative rather than pretending the reservation succeeded.
  4. Expected output: No seats available

Best practices

  • Choose exception names that describe the failed condition.
  • Preserve the original cause when wrapping another exception.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading