Checked or unchecked for your own exceptions
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When you write your own exception class, its parent decides how callers must treat it. Extend Exception and every caller must catch or declare it; extend RuntimeException and the compiler leaves callers free. Choosing well keeps errors visible without filling the code with try blocks.
Checked: a recoverable problem the caller must handle
A checked exception extends Exception but not RuntimeException. The Java compiler forces every caller to catch it or declare it with throws.
A checked exception is one the compiler makes every caller deal with: catch it, or declare it with throws. Your own exception is checked when it extends Exception (but not RuntimeException).
Example 1 · Checked: the train is full
import java.util.HashMap;import java.util.Map;
class SeatUnavailableException extends Exception { SeatUnavailableException(String train, int wanted, int left) { super("Not enough seats on " + train + ": wanted " + wanted + ", left " + left); }}
public class CheckedBookingDemo { static Map<String, Integer> seatsLeft = new HashMap<>();
static void book(String train, int seats) throws SeatUnavailableException { int left = seatsLeft.getOrDefault(train, 0); if (seats > left) { throw new SeatUnavailableException(train, seats, left); } seatsLeft.put(train, left - seats); System.out.println("Booked " + seats + " seats on " + train); }
public static void main(String[] args) { seatsLeft.put("12951 Rajdhani", 3); int[] requests = {2, 2}; for (int seats : requests) { try { book("12951 Rajdhani", seats); } catch (SeatUnavailableException e) { System.out.println(e.getMessage()); System.out.println("Offering the waiting list instead"); } } }}Booked 2 seats on 12951 Rajdhani Not enough seats on 12951 Rajdhani: wanted 2, left 1 Offering the waiting list instead
What this code does
SeatUnavailableException extends Exception, so it is checked:bookmust saythrows SeatUnavailableException, andmainmust catch it or the file does not compile.- A full train is not a bug. The caller has a sensible next step, offering the waiting list, which is exactly when a checked exception fits.
Make it checked for a problem that is not a bug, that a careful caller can expect, and that the caller can do something about. A full train, a declined payment or a missing file are normal events in a working program. The caller can offer the waiting list, ask for another account or pick a different file. If a caller forgets, the build fails with unreported exception SeatUnavailableException; must be caught or declared to be thrown. That error is the point: the compiler reminds every caller that this can happen.
Fix the error
Fix the checked exception
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
issue throws a checked exception but does not say so.
Error
FixDemo1.java:6: error: unreported exception FeeDueException; must be caught or declared to be thrown
throw new FeeDueException();
^Unchecked: programming bugs and broken rules
An unchecked exception extends RuntimeException or Error. The Java compiler does not force callers to handle it, so it is used for bugs and broken rules.
An unchecked exception extends RuntimeException. The compiler does not force anyone to catch or declare it.
Example 2 · Unchecked: marks that cannot be right
class InvalidMarksException extends RuntimeException { InvalidMarksException(int marks) { super("Marks must be 0 to 100, got " + marks); }}
public class UncheckedMarksDemo { // No "throws" needed: InvalidMarksException is unchecked static String grade(int marks) { if (marks < 0 || marks > 100) { throw new InvalidMarksException(marks); } if (marks >= 90) return "A"; if (marks >= 75) return "B"; if (marks >= 40) return "C"; return "F"; }
public static void main(String[] args) { System.out.println(grade(92)); System.out.println(grade(48)); try { System.out.println(grade(920)); // a typing slip: 92 became 920 } catch (InvalidMarksException e) { System.out.println("Bug found: " + e.getMessage()); } }}A C Bug found: Marks must be 0 to 100, got 920
What this code does
grade(92)andgrade(48)compile without anytry, because the compiler does not track unchecked exceptions.- Marks of 920 mean the calling code has a bug.
maincatches it here only to print the message; in a real program it would reach the top-level handler and someone would fix the input code.
Use it when the problem means the code is wrong: marks of 920 in a grading method, a negative quantity, a null where a name is required, or calling submit() on an exam that was never started. No caller can "recover" from its own bug at run time. The right reaction is to stop with a clear message and fix the code. Often you do not need a new class at all. The JDK already has IllegalArgumentException (bad argument), IllegalStateException (wrong time to call) and NullPointerException. The next lessons use them a lot.
How modern Java code leans to unchecked
Checked exceptions have a cost. Every method between the thrower and the handler must repeat throws, so one change deep inside a program can change ten method headers.
Example 3 · Unchecked exceptions pass through a stream
import java.util.List;
class MarksFileException extends RuntimeException { MarksFileException(String roll) { super("No marks file for roll " + roll); }}
public class LambdaFriendlyDemo { // If this threw a checked exception, the map(...) calls below would not compile: // "unreported exception ...; must be caught or declared to be thrown" static int loadMarks(String roll) { if (roll.startsWith("X")) { throw new MarksFileException(roll); } return 60 + roll.length() * 5; }
public static void main(String[] args) { List<String> good = List.of("101", "1022"); System.out.println(good.stream().map(LambdaFriendlyDemo::loadMarks).toList());
List<String> bad = List.of("101", "X9", "1022"); try { System.out.println(bad.stream().map(LambdaFriendlyDemo::loadMarks).toList()); } catch (MarksFileException e) { System.out.println("Stopped: " + e.getMessage()); } }}[75, 80] Stopped: No marks file for roll X9
What this code does
maptakes aFunction, andFunction.applydeclares no checked exceptions. An uncheckedMarksFileExceptionis allowed to fly out of the lambda.- The exception stops the whole stream and is caught once, outside it. With a checked exception you would need a
tryinside every lambda instead.
They also do not pass through lambdas. Function.apply, the method behind map, declares no checked exceptions, so a lambda that throws IOException inside a stream does not compile. Java 8 added UncheckedIOException for exactly this reason: Files.lines uses it to report read errors from inside a stream. So most newer libraries and frameworks throw unchecked exceptions, and languages such as Kotlin and C# have no checked exceptions at all. Checked exceptions are still right for a few expected, recoverable problems, especially in code other people call.
When would you make an exception checked?
Ask two questions about the problem: can a correct caller expect it, and can that caller do something useful about it? If both are yes, a checked exception fits; for a bug or a broken rule, make it unchecked.
Example 4 · Both kinds in one UPI service
class PaymentDeclinedException extends Exception { PaymentDeclinedException(String reason) { super("Payment declined: " + reason); }}
class UpiService { private int balance = 500; // whole rupees, so int is fine here
void pay(String toUpiId, int amount) throws PaymentDeclinedException { if (amount <= 0) { throw new IllegalArgumentException("amount must be positive, got " + amount); } if (amount > balance) { throw new PaymentDeclinedException("insufficient balance"); } balance -= amount; System.out.println("Paid Rs " + amount + " to " + toUpiId + ", balance Rs " + balance); }}
public class UpiDesignDemo { public static void main(String[] args) { UpiService upi = new UpiService(); int[] amounts = {120, 900, -50}; for (int amount : amounts) { try { upi.pay("shop@okbank", amount); } catch (PaymentDeclinedException e) { System.out.println(e.getMessage() + ". Try another account."); } catch (IllegalArgumentException e) { System.out.println("Bug in caller: " + e.getMessage()); } } }}Paid Rs 120 to shop@okbank, balance Rs 380 Payment declined: insufficient balance. Try another account. Bug in caller: amount must be positive, got -50
What this code does
- Low balance is an expected event with a clear next step (another account), so
PaymentDeclinedExceptionis checked and appears in thethrowsclause. - A negative amount can only come from a bug in the calling code, so it is the unchecked
IllegalArgumentException. Nothrowsis needed for it.
A result value such as Optional is another good fit when both answers are yes.
- Checked: seat sold out, payment declined, file chosen by the user is missing. The caller retries, asks again or offers another choice.
- Unchecked: negative amount,
nullname, method called in the wrong order. The caller fixes its code. - Leans unchecked: the error must travel through lambdas, streams or many layers.
- A real interview answer names one example of each and says why.
Next step
Check your understanding
12 quick questions