Exceptions: a custom unchecked exception skips the throws clause entirely

Extending RuntimeException makes a custom exception unchecked: it can be thrown from any method without a throws declaration and callers are free to ignore it, which suits programmer errors rather than recoverable conditions.

Code
class NegativeQuantityException extends RuntimeException {
    NegativeQuantityException(int quantity) {
        super("quantity cannot be negative: " + quantity);
    }
}
static int order(int quantity) {
    if (quantity < 0) {
        throw new NegativeQuantityException(quantity);
    }
    return quantity;
}
try {
    order(-3);
} catch (NegativeQuantityException e) {
    System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
}
Output
NegativeQuantityException: quantity cannot be negative: -3
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms