Exceptions in depth: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most exception bugs in real code come from a short list: wrong guesses about the order of try, catch and finally, catch blocks in the wrong order, a missing throws, and wrapped exceptions that lost their cause. Each one has a quick and reliable fix.
Tracing nested try, catch and finally
To trace nested blocks, follow the exception outward one level at a time. The inner try gets the first chance: only its own catch blocks are checked. If none matches, the inner finally runs, and only then does the exception reach the outer catch blocks.
Example 1 · Trace a nested try with numbered steps
public class NestedTraceDemo { static int step = 0;
static void log(String s) { step++; System.out.println(step + ". " + s); }
static int collect(String feeText) { try { log("outer try"); try { log("inner try"); int fee = Integer.parseInt(feeText); log("parsed " + fee); return fee; } catch (ArithmeticException e) { log("inner catch"); return -1; } finally { log("inner finally"); } } catch (NumberFormatException e) { log("outer catch: " + e.getMessage()); return 0; } finally { log("outer finally"); } }
public static void main(String[] args) { System.out.println("result = " + collect("4500")); step = 0; System.out.println("result = " + collect("45OO")); }}1. outer try 2. inner try 3. parsed 4500 4. inner finally 5. outer finally result = 4500 1. outer try 2. inner try 3. inner finally 4. outer catch: For input string: "45OO" 5. outer finally result = 0
What this code does
- With
"4500", thereturn fee;saves 4500, then bothfinallyblocks run, inner first, beforemainprints the result. - With
"45OO", the innercatchhandles onlyArithmeticException, so the innerfinallyruns and theNumberFormatExceptionmoves out to the outercatch. Step 3 is the innerfinally, before the outercatch.
The same order holds for return. A return inside the inner try runs the inner finally, then the outer finally, and only then does the method give back the saved value. Number your print lines while tracing; most mistakes come from putting a finally line too late.
Fixing catch order and missing throws
Two compiler errors cover most beginner exception code: exception X has already been caught (move the child catch above its parent) and unreported exception X; must be caught or declared to be thrown (add a try-catch or a throws X).
Example 2 · Two compiler errors in one program
import java.io.FileNotFoundException;import java.io.IOException;
public class TwoMistakesDemo { static String readHallTicket(String roll) throws IOException { if (roll.isEmpty()) { throw new FileNotFoundException("hall ticket not found"); } return "Hall ticket for " + roll; }
static void printTicket(String roll) { System.out.println(readHallTicket(roll)); }
public static void main(String[] args) { try { printTicket("CS101"); System.out.println(readHallTicket("")); } catch (IOException e) { System.out.println("Could not read: " + e.getMessage()); } catch (FileNotFoundException e) { System.out.println("No ticket yet"); } }}TwoMistakesDemo.java:13: error: unreported exception IOException; must be caught or declared to be thrown
System.out.println(readHallTicket(roll));
^
TwoMistakesDemo.java:22: error: exception FileNotFoundException has already been caught
} catch (FileNotFoundException e) {
^
2 errorsWhat this code does
- Line 13:
printTicketcalls a method thatthrows IOExceptionbut neither catches nor declares it. - Line 22:
FileNotFoundExceptionis a child ofIOException, so itscatchafter theIOExceptionone can never run.
Example 3 · Both errors fixed
import java.io.FileNotFoundException;import java.io.IOException;
public class TwoMistakesFixedDemo { static String readHallTicket(String roll) throws IOException { if (roll.isEmpty()) { throw new FileNotFoundException("hall ticket not found"); } return "Hall ticket for " + roll; }
static void printTicket(String roll) throws IOException { System.out.println(readHallTicket(roll)); }
public static void main(String[] args) { try { printTicket("CS101"); System.out.println(readHallTicket("")); } catch (FileNotFoundException e) { System.out.println("No ticket yet"); } catch (IOException e) { System.out.println("Could not read: " + e.getMessage()); } }}Hall ticket for CS101 No ticket yet
What this code does
printTicketnow declaresthrows IOException, so the decision moves tomain, which already has atry.- The child
catch (FileNotFoundException e)now comes first, so a missing ticket gets its own message, and other read problems fall to theIOExceptionblock.
Fix them one at a time and compile again. Adding throws often moves the second error to the caller, which is expected: the caller now has to decide.
Adding causes to wrapped exceptions
Every throw new X(...) inside a catch should pass the caught exception as the cause: throw new ImportException("cannot import row: " + row, e);. Without it, getCause() is null and the trace has no Caused by: block, so the real reason disappears.
Example 4 · Add the cause and narrow the catch
class ImportException extends Exception { ImportException(String message) { super(message); }
ImportException(String message, Throwable cause) { super(message, cause); }}
public class AddCauseDemo { static int parseRow(String row) { return Integer.parseInt(row.split(",")[1].trim()); }
static int importBad(String row) throws ImportException { try { return parseRow(row); } catch (RuntimeException e) { throw new ImportException("cannot import row: " + row); } }
static int importGood(String row) throws ImportException { try { return parseRow(row); } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) { throw new ImportException("cannot import row: " + row, e); } }
public static void main(String[] args) { String[] rows = {"Asha", "Ravi, 7x"}; for (String row : rows) { try { importBad(row); } catch (ImportException e) { System.out.println("bad: " + e.getMessage() + " | cause: " + e.getCause()); } try { importGood(row); } catch (ImportException e) { System.out.println("good: " + e.getMessage() + " | cause: " + e.getCause()); } } }}bad: cannot import row: Asha | cause: null good: cannot import row: Asha | cause: java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 bad: cannot import row: Ravi, 7x | cause: null good: cannot import row: Ravi, 7x | cause: java.lang.NumberFormatException: For input string: "7x"
What this code does
- The bad version gives the same message for both rows and no cause, so nobody can tell a missing comma from a bad number.
- The good version passes
e, and its multi-catch names the two expected problems. A real bug such as aNullPointerExceptionwould not be caught and turned into an "import" error.
While fixing, also narrow the catch. catch (RuntimeException e) around a parse also hides real bugs such as a NullPointerException. Catch the types you expect, usually with multi-catch.
Interview: checked versus unchecked, throw versus throws
These two questions come up in almost every Java interview, so have a short, exact answer ready for each.
Example 5 · throw, throws, checked and unchecked in one place
import java.io.IOException;
public class ThrowVsThrowsDemo { // throws: a label on the method for a checked exception static String downloadMarksheet(String roll) throws IOException { if (roll.endsWith("9")) { throw new IOException("server not reachable"); // throw: one object, now } return "marksheet-" + roll + ".pdf"; }
// no throws needed: IllegalArgumentException is unchecked static void checkRoll(String roll) { if (!roll.startsWith("CS")) { throw new IllegalArgumentException("not a CS roll: " + roll); } }
public static void main(String[] args) { String[] rolls = {"CS101", "EE102", "CS109"}; for (String roll : rolls) { try { checkRoll(roll); System.out.println(downloadMarksheet(roll)); } catch (IOException e) { System.out.println("retry later: " + e.getMessage()); } catch (IllegalArgumentException e) { System.out.println("fix the input: " + e.getMessage()); } } }}marksheet-CS101.pdf fix the input: not a CS roll: EE102 retry later: server not reachable
What this code does
downloadMarksheetmust declarethrows IOException, a checked problem outside the program's control.checkRollthrows an uncheckedIllegalArgumentException, so it needs nothrows.- The two catch blocks match the two kinds of problem: "retry later" for the outside failure, "fix the input" for the bad argument.
- Checked: under
Exceptionbut notRuntimeException, such asIOException; the compiler forces catch orthrows. Unchecked:RuntimeException, its subclasses andError; no compiler rule. - Checked usually means a problem outside your control (file, network). Unchecked usually means a bug or bad argument.
throwis a statement that throws one object now:throw new IOException("...").throwsis part of the method header that lists checked exceptions the method may pass to its caller.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Predict the output, then run it to check.
static void attempt(int marks) { try { System.out.println("checking " + marks); if (marks < 0) throw new IllegalArgumentException("negative marks"); System.out.println("valid"); } catch (IllegalArgumentException e) { System.out.println("error: " + e.getMessage()); } finally { System.out.println("done " + marks); }}// main: attempt(72); attempt(-5);checking 72 valid done 72 checking -5 error: negative marks done -5
Exercise 2· Easy
This does not compile: showCountdown calls Thread.sleep. Make showCountdown declare the exception, and handle it in main by printing countdown stopped. The program prints the countdown for the college fest.
static void showCountdown(int from) { for (int i = from; i >= 1; i--) { System.out.println("Fest starts in " + i); Thread.sleep(10); } System.out.println("Fest is live");}Fest starts in 3 Fest starts in 2 Fest starts in 1 Fest is live
Exercise 3· Medium
Fix this recharge program: the catch order does not compile, and the two blocks that print the same message should become one multi-catch. The program works out how many recharges of a plan fit in a Rs 600 budget. Test it with the plan texts "199", "1g9" and "0".
try { int plan = Integer.parseInt(text); System.out.println("Rs " + plan + " plan: " + (600 / plan) + " recharges fit in Rs 600");} catch (RuntimeException e) { System.out.println("Recharge failed");} catch (NumberFormatException e) { System.out.println("Invalid amount: " + text);} catch (ArithmeticException e) { System.out.println("Invalid amount: " + text);}Rs 199 plan: 3 recharges fit in Rs 600 Invalid amount: 1g9 Invalid amount: 0
Exercise 4· Medium
loadAttendance wraps errors but loses them. Add the cause, narrow the catch to the two expected types, and print the wrapper message and the cause's simple class name for the rows "CS101:22", "CS102" and "CS103:2x".
static int loadAttendance(String row) { try { return Integer.parseInt(row.split(":")[1]); } catch (RuntimeException e) { throw new IllegalStateException("bad attendance row " + row); }}CS101:22 -> 22 days bad attendance row CS102 (cause: ArrayIndexOutOfBoundsException) bad attendance row CS103:2x (cause: NumberFormatException)
Exercise 5· Medium
This method always reports success because of its finally. Fix it so a failed SMS reaches the caller, while attempts is still counted on every call. Print the result of sending to 9876543210 and to 98765, then the attempt count.
static int attempts = 0;static String sendSms(String phone) { try { if (phone.length() != 10) { throw new IllegalArgumentException("invalid number " + phone); } return "SMS sent to " + phone; } finally { attempts++; return "SMS sent to " + phone; }}SMS sent to 9876543210 failed: invalid number 98765 attempts: 2
Exercise 6· Medium
Read result PDFs for the rolls CS101, CS102, CS104 with a stream. static String readPdf(String roll) throws IOException throws IOException("result for " + roll + " not published") for CS104. Write static List<String> readAll(List<String> rolls) throws IOException that uses a wrapping helper in map and unwraps outside the stream. In main, print the list for the first two rolls, then the error for all three.
[CS101.pdf, CS102.pdf] IOException: result for CS104 not published
Exercise 7· Hard
Predict the full output of this loop. Watch the continue, the break and where each finally line appears.
for (int day = 1; day <= 4; day++) { try { if (day == 2) { System.out.println("day 2: holiday"); continue; } if (day == 4) { System.out.println("day 4: exams cancelled"); break; } int classes = 12 / (3 - day); System.out.println("day " + day + ": " + classes + " classes"); } catch (ArithmeticException e) { System.out.println("day " + day + ": timetable error"); } finally { System.out.println("day " + day + ": attendance saved"); }}System.out.println("week over");day 1: 6 classes day 1: attendance saved day 2: holiday day 2: attendance saved day 3: timetable error day 3: attendance saved day 4: exams cancelled day 4: attendance saved week over
Exercise 8· Hard
Build a small exam-result portal with the right exception for each case. A checked ResultNotPublishedException (with a cause constructor) for results that are not out yet; IllegalArgumentException for a roll that is not 5 characters; Optional for an unknown roll. ResultStore.fetch(roll) throws IOException("server busy") for CS103; Portal.result(roll) validates the roll, returns Optional.empty() for an unknown roll, and wraps the IOException as ResultNotPublishedException("result for CS103 is not available", e). For CS101, CS1, CS999, CS103, print the result, invalid roll: ..., no such student: ... or <message> (root: <root message>).
CS101: 88 marks invalid roll: CS1 no such student: CS999 result for CS103 is not available (root: server busy)
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of Exceptions in Depth
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Resources and why they must be closed