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.
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());
}
NegativeQuantityException: quantity cannot be negative: -3
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