Unchecked Exception in Java
beginner· Exceptions · Error Handling
Problem
An unchecked exception extends RuntimeException, and the compiler never requires it to be caught or declared — code compiles fine whether or not it's handled.
Reject an invalid argument by throwing an unchecked exception, and catch it at the call site.
Input
age = -5
Output
Error: Age cannot be negative
Java Program
Java
public class UncheckedExceptionDemo {
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative"); // unchecked — no throws clause needed here
}
System.out.println("Age set to " + age);
}
public static void main(String[] args) {
try {
setAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}Output
Error: Age cannot be negative
Core Logic
Throwing IllegalArgumentException when a precondition fails signals a programming/usage error without forcing every caller to prove they've handled it.
How It Works
- 1
setAge(int age)checksage < 0and throwsIllegalArgumentExceptionif the check fails. - 2
IllegalArgumentExceptionextendsRuntimeException, making it unchecked —setAgeneeds nothrowsclause, and this code would compile even with notry/catcharound the call at all. - 3The caller here chooses to wrap the call in
try/catchanyway, but that's a choice, not a compiler requirement. - 4
catch (IllegalArgumentException e)receives the exception and reads its message back.
Calling
setAge(-5) throws immediately, caught and printed as "Error: Age cannot be negative".💡
Key Point: Removing the try/catch entirely and letting the exception propagate uncaught would still compile — that's the defining difference from a checked exception, which the compiler refuses to allow unhandled.
Key Concepts
unchecked exceptionIllegalArgumentExceptionRuntimeException