Java ProgramsExceptionsUnchecked Exception

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. 1setAge(int age) checks age < 0 and throws IllegalArgumentException if the check fails.
  2. 2IllegalArgumentException extends RuntimeException, making it unchecked — setAge needs no throws clause, and this code would compile even with no try/catch around the call at all.
  3. 3The caller here chooses to wrap the call in try/catch anyway, but that's a choice, not a compiler requirement.
  4. 4catch (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

Related Programs