bhylu.com

Advertisements

Java Express a Domain Failure Clearly

throw creates an exceptional exit at a particular point. throws declares part of a method’s possible checked-exception contract; it does not itself throw anything.

Understand the idea

Use a meaningful exception type and message when a caller violates a method’s precondition. An application-specific checked exception can represent a recoverable operation failure, but introducing one should clarify the API rather than create boilerplate. Preserve the cause when wrapping a lower-level exception so the original diagnostic information is not lost. Do not leak private input or credentials into a public message.

Run it locally

Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.

JDK and terminal setup

javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out Main

A worked example

Java 21+ · Main.java

public class Main {
    static void requireSeats(int requested) {
        if (requested <= 0) throw new IllegalArgumentException("Choose at least one seat");
    }

    public static void main(String[] args) {
        try {
            requireSeats(0);
        } catch (IllegalArgumentException failure) {
            System.out.println(failure.getMessage());
        }
    }
}

Expected output

Choose at least one seat

The method has a simple input contract and rejects a non-positive request. IllegalArgumentException is unchecked, so it does not require a throws clause. A method doing file I/O may declare IOException, and a caller must then choose an appropriate handling boundary. Neither style automatically makes a domain model more reliable without clear rules.

Check the official Java documentation for detailed contracts and supported options.