Checked and unchecked exceptions
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Reading a file forces you to handle a possible error, but dividing by zero does not. Why does Java treat some errors so differently?
The handle-or-declare rule
A checked exception is one the compiler forces you to catch or declare with throws, such as IOException; unchecked exceptions are RuntimeException and its subclasses.
The handle-or-declare rule says: if a statement can throw a checked exception, its method must either catch it (handle) or list it after throws (declare). The compiler checks this before the program ever runs.
Example 1 · Handle it or declare it
import java.io.IOException;
public class HandleOrDeclareDemo { // stands in for reading a marks file from disk static int readMarks(String roll) throws IOException { if (roll.isEmpty()) { throw new IOException("no roll number given"); } return 70 + roll.length(); }
// Choice 1: handle it here with try-catch static void printMarks(String roll) { try { System.out.println(roll + ": " + readMarks(roll)); } catch (IOException e) { System.out.println("Could not read marks: " + e.getMessage()); } }
// Choice 2: declare it and let the caller decide static int totalOfTwo(String a, String b) throws IOException { return readMarks(a) + readMarks(b); }
public static void main(String[] args) { printMarks("CS101"); printMarks(""); try { System.out.println("Total: " + totalOfTwo("CS101", "CS2")); System.out.println("Total: " + totalOfTwo("CS101", "")); } catch (IOException e) { System.out.println("main caught: " + e.getMessage()); } }}CS101: 75 Could not read marks: no roll number given Total: 148 main caught: no roll number given
What this code does
printMarkshandles the exception itself, so its header has nothrows, and its callers do not need atry.totalOfTwodeclaresthrows IOExceptionand has notry. The exception fromreadMarks("")passes through it tomain, which must handle it.
Handling means a try-catch around the call, with a useful answer in the catch: a message, a default value, a second try. Declaring means "I cannot deal with this here; my caller must". The exception then moves up to the method that called this one, and the same rule applies there. The point of the rule is that problems outside your control, such as a missing file or a dropped network, cannot be forgotten. The compiler will not let a program ignore them by accident.
The throws clause
A throws clause is the part of a method header that lists the checked exceptions the method may pass to its caller: static String load(String day) throws IOException. Several types are separated by commas.
Example 2 · throws with two types, and a parent covering a child
import java.io.FileNotFoundException;import java.io.IOException;
public class ThrowsChainDemo { static String openTimetable(String day) throws FileNotFoundException { if (day.equals("Sunday")) { throw new FileNotFoundException("timetable-" + day + ".txt"); } return "Timetable for " + day; }
// IOException also covers FileNotFoundException, its child static String loadTimetable(String day) throws IOException, InterruptedException { if (day.isBlank()) { throw new InterruptedException("loading stopped"); } return openTimetable(day); }
public static void main(String[] args) { String[] days = {"Monday", "Sunday", " "}; for (String day : days) { try { System.out.println(loadTimetable(day)); } catch (IOException e) { System.out.println("File problem: " + e.getMessage()); } catch (InterruptedException e) { System.out.println("Stopped: " + e.getMessage()); } } }}Timetable for Monday File problem: timetable-Sunday.txt Stopped: loading stopped
What this code does
loadTimetablecallsopenTimetable, which may throwFileNotFoundException. Declaring the parentIOExceptionis enough to satisfy the rule.- Two checked types are declared, separated by a comma, so
mainhandles both: onecatchfor each.
Do not mix it up with throw. throw is a statement that throws one exception object right now. throws is a label on the method that warns callers what may come out of it. Declaring a parent class covers all its children. A method with throws IOException may pass on a FileNotFoundException, because that class is below IOException in the tree.
public static void main(String[] args) throws IOException compiles. If the exception does happen, the JVM prints the stack trace and the program stops.RuntimeException and its subclasses are unchecked
An unchecked exception is a RuntimeException, any of its subclasses, or an Error. The compiler does not ask you to catch or declare them, so a method can throw IllegalArgumentException without a throws clause.
Example 3 · An unchecked exception needs no throws
public class UncheckedDemo { static int berthsLeft(int total, int booked) { if (booked > total) { throw new IllegalArgumentException("booked " + booked + " is more than " + total); } return total - booked; }
public static void main(String[] args) { System.out.println("Berths left: " + berthsLeft(72, 60)); // compiles with no try
try { System.out.println("Berths left: " + berthsLeft(72, 80)); } catch (IllegalArgumentException e) { System.out.println("Booking error: " + e.getMessage()); } }}Berths left: 12 Booking error: booked 80 is more than 72
What this code does
berthsLeftthrowsIllegalArgumentExceptionwith nothrowsclause. It is aRuntimeException, so the compiler does not check it.- The first call has no
tryand still compiles. The second call is wrapped only because this program wants a friendly message, not because the compiler asked.
The reason is practical. Almost any line could throw one: every . on an object could be a NullPointerException, every / an ArithmeticException. If all of them had to be declared, every method would need a long throws list. And they mostly mean a bug, which is fixed by changing the code, not by catching. You may still catch an unchecked exception when you have a real answer for it, such as bad text typed by a user. Listing one in throws is allowed too, but only as documentation.
Compiler error: unreported exception
unreported exception X; must be caught or declared to be thrown is the compiler's message when the handle-or-declare rule is broken. It points at the exact line, and names the checked exception that is not dealt with.
Example 4 · Two unreported exceptions
import java.io.IOException;
public class UnreportedDemo { static int readFee(String roll) { if (roll.isEmpty()) { throw new IOException("fee file missing"); } return 45000; }
public static void main(String[] args) { System.out.println("Checking fee..."); Thread.sleep(500); System.out.println(readFee("CS101")); }}UnreportedDemo.java:6: error: unreported exception IOException; must be caught or declared to be thrown
throw new IOException("fee file missing");
^
UnreportedDemo.java:13: error: unreported exception InterruptedException; must be caught or declared to be thrown
Thread.sleep(500);
^
2 errorsWhat this code does
- Line 6 throws a checked
IOExceptionin a method with nothrows. Line 13 callsThread.sleep, which declaresthrows InterruptedException, without atry. - Fix
readFeewiththrows IOException, and the error moves tomain, the caller. Then fixmainwith atry-catchfor both types, or withthrows IOException, InterruptedException.
- The exception can come from your own
throw new IOException(...)or from a library method that declares it, such asThread.sleep, which throwsInterruptedException. - Fix 1: wrap the call in
try-catchwhen this method can do something useful about the problem. - Fix 2: add
throws Xto the method header when only the caller knows what to do. The caller then gets the same rule. - The opposite mistake also fails: catching a checked exception that the
tryblock can never throw givesexception X is never thrown in body of corresponding try statement.
Fix the error
Fix the unreported exception
Read the error, then pick the line that fixes it.
Round 1 of 2
save() declares a checked exception. Pick the line that makes main compile.
Error
Report.java:7: error: unreported exception IOException; must be caught or declared to be thrown
save();
^Next step
Check your understanding
12 quick questions