Part 06 / Stage 1
Exceptions basics
Goal: Stop letting a bad PIN or a typo crash your program. Learn try/catch/finally, tell checked exceptions apart from unchecked ones at a practical level, throw your own exception, and read a real stack trace line by line. Time: ~4 hours
What you will learn
- What an exception is, and what the JVM does when nothing catches one
try/catch: catching one exception type, and several- Catch order, and multi-catch with
| finally: code that always runs, even after areturnor an uncaught error- Checked vs. unchecked exceptions — the practical difference, not the whole hierarchy
- Writing and throwing your own exception class
- Reading a stack trace: which line is "mine", which line is the real cause
- Building safe PIN and amount input for an ATM, with a limited number of retries
About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in
../../TOOLING.md. Exception messages and stack trace formatting are JVM details; they are stable across JDK 21 builds but are not part of the Java language itself.
Topics in this part
Practice
Each exercise is its own class ExNN in its own solutions/exNN.java file (the stage-wide convention — see solutions/ex01.java), with a main(String[] args) method. Where a sample transcript shows typed input, feed it the same way shown in the lesson: printf 'line1\nline2\n' | java ClassName.
📁 About
examples/filenames: most examples follow the stage-wideNN_descriptive_name.javaconvention (e.g.01_try_catch_basics.java).NumberFormatCrash.java,ArrayIndexCrash.java,CustomExceptionDemo.java,StackTraceAnatomy.javaandCheckedWithoutHandling.javakeep their original PascalCase names instead, because each is shown crashing (or, forCheckedWithoutHandling.java, deliberately failing to compile) with real output that names the file directly — renaming them would mean faking that output instead of showing the real thing.
Exercise 1: Catch it or lose it
Scenario: A canteen app reads the number of plates ordered as text. A typo must not crash the till.
What to do: In main():
- Make a
String[]of inputs:{"12", "7a", "", "5"}. - For each one, try
Integer.parseInton it. If it works, printPlates: <n>. If it throwsNumberFormatException, catch it and printBad input "<text>": <message>. - After the loop, print
Valid orders: <count>— the number of inputs that parsed successfully.
Sample output:
Plates: 12
Bad input "7a": For input string: "7a"
Bad input "": For input string: ""
Plates: 5
Valid orders: 2
💡 Hint: Keep a counter outside the loop, increment it only in the success path (right after a successful parseInt, before the println).
Exercise 2: Most specific first
Scenario: A delivery app looks up the Nth stop on a route and divides the remaining fuel by the number of stops left. Two different mistakes can happen here. What to do:
- Write
fuelPerStop(int[] stops, int index, int fuel)that returnsfuel / stops[index]. - In
main(), call it withstops = {3, 0, 5},fuel = 100for these three cases, each in its owntry:index = 1(division by zero),index = 9(bad index),index = 2(works fine). - For each case, catch
ArithmeticExceptionandArrayIndexOutOfBoundsExceptionin separate catch blocks (most specific — here, order them so each prints its own clear message), printingDivide by zero at stop <index>orNo such stop: <index>. On success printFuel per stop: <value>.
Sample output:
Divide by zero at stop 1
No such stop: 9
Fuel per stop: 20
💡 Hint: ArrayIndexOutOfBoundsException happens when reading stops[index]; ArithmeticException happens on the division right after. Neither is a subtype of the other, so either catch order compiles — but put the one you want checked first, first.
Exercise 3: finally counts every attempt
Scenario: A quiz app must count every question attempt, right or wrong, for a final score report. What to do:
- Write
grade(String answerText, int correctAnswer)that parsesanswerTextto anintand returnstrueif it equalscorrectAnswer. - Outside the method, keep two counters:
attemptsandcorrect. - For each of
{"4", "abc", "5", "4"}againstcorrectAnswer = 4: callgradeinside atry; incrementattemptsin afinally(so it counts even when parsing fails); ifgradereturnedtrue, incrementcorrect; if parsing threwNumberFormatException, catch it and printSkipped "<text>": not a number. - Print
Attempts: <attempts>, Correct: <correct>.
Sample output:
Skipped "abc": not a number
Attempts: 4, Correct: 2
💡 Hint: finally runs whether the try succeeded or the catch ran, so attempts++ belongs there, not after the try/catch and not inside the try.
Exercise 4: Checked, on purpose
Scenario: A background job pauses between retries using Thread.sleep, which throws the checked InterruptedException.
What to do:
- Write
retryWithDelay(int attempt)that printsAttempt <attempt>: waiting..., callsThread.sleep(200), then printsAttempt <attempt>: done. - First, write it without any
try/catchorthrows, try to compile it, and copy the realjavacerror you get into a comment above the method. - Fix it by adding a
try/catcharoundThread.sleepthat catchesInterruptedExceptionand printsAttempt <attempt>: interrupted: <message>. - In
main(), callretryWithDelay(1)andretryWithDelay(2).
Sample output:
Attempt 1: waiting...
Attempt 1: done
Attempt 2: waiting...
Attempt 2: done
💡 Hint: The exact compiler message is in this lesson's section 5 (examples/CheckedWithoutHandling.java) — compile your own broken version first and check your error matches before you fix it.
Exercise 5: A custom exception for a school rule
Scenario: A school's marks-entry tool must reject any mark outside 0–100, with a clear reason. What to do:
- Write
InvalidMarkException extends RuntimeExceptionwith a constructor that takes aString messageand passes it tosuper(...). - Write
recordMark(String student, int mark)that throwsInvalidMarkExceptionwith message"<student>'s mark <mark> is below 0"or"<student>'s mark <mark> is above 100"as appropriate, and otherwise prints<student>: <mark>. - Call it for
("Asha", 91),("Ravi", -5),("Meera", 150), each in its owntry/catch, printingRejected: <message>for the caught ones. - After the loop, call
recordMark("Kiran", 200)uncaught, so the program ends with a stack trace.
Sample output (then a real, uncaught stack trace for Kiran — your line numbers will match your own file):
Asha: 91
Rejected: Ravi's mark -5 is below 0
Rejected: Meera's mark 150 is above 100
Exception in thread "main" InvalidMarkException: Kiran's mark 200 is above 100
at Ex05.recordMark(ex05.java:20)
at Ex05.main(ex05.java:35)
💡 Hint: Compile and run this one for real; paste the exact stack trace you get, not a guess — the class and method names in the at lines must match your actual file.
Exercise 6: Three strikes at the gate
Scenario: A housing society's gate app lets a resident retry a 6-digit access code up to 3 times before it logs them out. What to do:
- Write
TooManyCodeAttemptsException extends RuntimeExceptionwith a message constructor. - Write
readAccessCode(Scanner scanner)that loops up to 3 attempts: printEnter 6-digit code (attempt <n> of 3):, read a line, trim it. IfInteger.parseIntfails, catchNumberFormatExceptionand printNot a number: "<text>". Else if the length isn't 6, printCode must be 6 digits, got "<text>". Otherwisereturnthe code text. - If all 3 attempts fail, throw
TooManyCodeAttemptsException("Gate locked after 3 failed attempts."). - In
main(), call it inside atry/finally: on success printAccess granted: <code>; catch the lockout exception and print its message; infinallyprintGate session ended.either way.
Sample run (bad, bad, good):
$ printf 'abc\n12345\n482017\n' | java Ex06
Enter 6-digit code (attempt 1 of 3): Not a number: "abc"
Enter 6-digit code (attempt 2 of 3): Code must be 6 digits, got "12345"
Enter 6-digit code (attempt 3 of 3): Access granted: 482017
Gate session ended.
💡 Hint: This is the same shape as examples/05_safe_atm_input.java's readPin — one method, a bounded loop, two kinds of bad input handled differently, one exception thrown after the loop.
Exercise 7: The full safe-input helper, reusable for any ATM field
Scenario: Generalize examples/05_safe_atm_input.java so the same retry loop reads either a PIN or an amount, instead of writing it twice, using only what you know so far (static methods and primitive parameters — no interfaces or lambdas yet, that's Stage 2).
What to do:
- Write an unchecked exception
InvalidFieldExceptionthat carries the field's name in its message. - Write
int readValidatedInt(Scanner scanner, String prompt, int maxAttempts, int min, int max, int multipleOf, String fieldName)that: loops up tomaxAttemptstimes printingprompt; reads a line and trims it; onNumberFormatException, printsNot a number: "<text>"; otherwise checks the value is betweenminandmaxand a multiple ofmultipleOf(pass1for "no multiple restriction", since everyintis a multiple of1) — if not, printInvalid <fieldName>: <value>and loop again; otherwise return the value. AftermaxAttemptsfailures, throwInvalidFieldException("Too many bad attempts for " + fieldName). - In
main(), call it twice: once for a PIN (maxAttempts = 3,min = 1000,max = 9999,multipleOf = 1), once for an amount (maxAttempts = 3,min = 100,max = 100000,multipleOf = 100). - Wrap both calls in one
try/catch/finally, same shape as Exercise 6.
Sample run (one bad PIN, then good; one bad amount, then good):
$ printf '12\n4821\n250\n1500\n' | java Ex07
Enter 4-digit PIN (attempt 1 of 3): Invalid pin: 12
Enter 4-digit PIN (attempt 2 of 3): Accepted pin: 4821
Enter amount (attempt 1 of 3): Invalid amount: 250
Enter amount (attempt 2 of 3): Accepted amount: 1500
Session ended.
💡 Hint: The multiple check is value % multipleOf == 0. With multipleOf = 1 that is always true, so the same method works for a PIN (no multiple rule) and an amount (must be a multiple of 100) without a boolean flag or a lambda.
Show the solutions for Part 6 (7 files)
solutions/ex01.java
/*
* Exercise 1: Catch it or lose it.
* Run: javac ex01.java
* java Ex01
*/
class Ex01 {
public static void main(String[] args) {
String[] orders = {"12", "7a", "", "5"};
int validOrders = 0;
for (String text : orders) {
try {
int plates = Integer.parseInt(text);
System.out.println("Plates: " + plates);
validOrders++;
} catch (NumberFormatException e) {
System.out.println("Bad input \"" + text + "\": " + e.getMessage());
}
}
System.out.println("Valid orders: " + validOrders);
}
}
solutions/ex02.java
/*
* Exercise 2: Most specific first.
* Run: javac ex02.java
* java Ex02
*/
class Ex02 {
static int fuelPerStop(int[] stops, int index, int fuel) {
return fuel / stops[index];
}
static void tryStop(int[] stops, int index, int fuel) {
try {
int perStop = fuelPerStop(stops, index, fuel);
System.out.println("Fuel per stop: " + perStop);
} catch (ArithmeticException e) {
System.out.println("Divide by zero at stop " + index);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("No such stop: " + index);
}
}
public static void main(String[] args) {
int[] stops = {3, 0, 5};
int fuel = 100;
tryStop(stops, 1, fuel); // stops[1] == 0 -> ArithmeticException
tryStop(stops, 9, fuel); // no index 9 -> ArrayIndexOutOfBoundsException
tryStop(stops, 2, fuel); // fine
}
}
solutions/ex03.java
/*
* Exercise 3: finally counts every attempt.
* Run: javac ex03.java
* java Ex03
*/
class Ex03 {
static boolean grade(String answerText, int correctAnswer) {
int answer = Integer.parseInt(answerText);
return answer == correctAnswer;
}
public static void main(String[] args) {
String[] answers = {"4", "abc", "5", "4"};
int correctAnswer = 4;
int attempts = 0;
int correct = 0;
for (String answerText : answers) {
try {
if (grade(answerText, correctAnswer)) {
correct++;
}
} catch (NumberFormatException e) {
System.out.println("Skipped \"" + answerText + "\": not a number");
} finally {
attempts++;
}
}
System.out.println("Attempts: " + attempts + ", Correct: " + correct);
}
}
solutions/ex04.java
/*
* Exercise 4: Checked, on purpose.
*
* The first version of retryWithDelay had no try/catch and no "throws":
*
* static void retryWithDelay(int attempt) {
* System.out.println("Attempt " + attempt + ": waiting...");
* Thread.sleep(200);
* System.out.println("Attempt " + attempt + ": done");
* }
*
* Real javac output on that version (captured on javac 21.0.11):
*
* Ex4Broken.java:4: error: unreported exception InterruptedException; must be caught or declared to be thrown
* Thread.sleep(200);
* ^
* 1 error
*
* Fixed below with a try/catch around Thread.sleep.
*
* Run: javac ex04.java
* java Ex04
*/
class Ex04 {
static void retryWithDelay(int attempt) {
System.out.println("Attempt " + attempt + ": waiting...");
try {
Thread.sleep(200);
System.out.println("Attempt " + attempt + ": done");
} catch (InterruptedException e) {
System.out.println("Attempt " + attempt + ": interrupted: " + e.getMessage());
}
}
public static void main(String[] args) {
retryWithDelay(1);
retryWithDelay(2);
}
}
solutions/ex05.java
/*
* Exercise 5: A custom exception for a school rule.
* Run: javac ex05.java
* java Ex05
*/
class InvalidMarkException extends RuntimeException {
InvalidMarkException(String message) {
super(message);
}
}
class Ex05 {
static void recordMark(String student, int mark) {
if (mark < 0) {
throw new InvalidMarkException(student + "'s mark " + mark + " is below 0");
}
if (mark > 100) {
throw new InvalidMarkException(student + "'s mark " + mark + " is above 100");
}
System.out.println(student + ": " + mark);
}
public static void main(String[] args) {
String[][] rows = {{"Asha", "91"}, {"Ravi", "-5"}, {"Meera", "150"}};
for (String[] row : rows) {
try {
recordMark(row[0], Integer.parseInt(row[1]));
} catch (InvalidMarkException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
recordMark("Kiran", 200); // uncaught on purpose
}
}
solutions/ex06.java
import java.util.Scanner;
/*
* Exercise 6: Three strikes at the gate.
* Run: javac ex06.java
* java Ex06
* Then type a 6-digit code when asked (see exercises.md for a sample
* transcript with bad input, fed via printf | java).
*/
class TooManyCodeAttemptsException extends RuntimeException {
TooManyCodeAttemptsException(String message) {
super(message);
}
}
class Ex06 {
static final int MAX_ATTEMPTS = 3;
static String readAccessCode(Scanner scanner) {
for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
System.out.print("Enter 6-digit code (attempt " + attempt + " of " + MAX_ATTEMPTS + "): ");
String text = scanner.nextLine().trim();
try {
Integer.parseInt(text);
if (text.length() != 6) {
System.out.println(" Code must be 6 digits, got \"" + text + "\"");
continue;
}
return text;
} catch (NumberFormatException e) {
System.out.println(" Not a number: \"" + text + "\"");
}
}
throw new TooManyCodeAttemptsException("Gate locked after 3 failed attempts.");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
String code = readAccessCode(scanner);
System.out.println("Access granted: " + code);
} catch (TooManyCodeAttemptsException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
System.out.println("Gate session ended.");
}
}
}
solutions/ex07.java
import java.util.Scanner;
/*
* Exercise 7: The full safe-input helper, reusable for any ATM field.
* One generic method validates both a PIN and an amount, using only
* static methods and primitive parameters (no interfaces/lambdas).
*
* Run: javac ex07.java
* java Ex07
* Then type values when asked (see exercises.md for a sample transcript
* with bad input, fed via printf | java).
*/
class InvalidFieldException extends RuntimeException {
InvalidFieldException(String message) {
super(message);
}
}
class Ex07 {
static int readValidatedInt(Scanner scanner, String prompt, int maxAttempts,
int min, int max, int multipleOf, String fieldName) {
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
System.out.print(prompt + " (attempt " + attempt + " of " + maxAttempts + "): ");
String text = scanner.nextLine().trim();
try {
int value = Integer.parseInt(text);
if (value < min || value > max || value % multipleOf != 0) {
System.out.println(" Invalid " + fieldName + ": " + value);
continue;
}
return value;
} catch (NumberFormatException e) {
System.out.println(" Not a number: \"" + text + "\"");
}
}
throw new InvalidFieldException("Too many bad attempts for " + fieldName);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int pin = readValidatedInt(scanner, "Enter 4-digit PIN", 3, 1000, 9999, 1, "pin");
System.out.println("Accepted pin: " + pin);
int amount = readValidatedInt(scanner, "Enter amount", 3, 100, 100_000, 100, "amount");
System.out.println("Accepted amount: " + amount);
} catch (InvalidFieldException e) {
System.out.println(e.getMessage());
} finally {
scanner.close();
System.out.println("Session ended.");
}
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Catching Exception first, specific type second |
javac rejects it: the specific catch could never run |
List the most specific exception types first, catch-all last |
catch (Exception e) {} with an empty body |
Swallows every error silently; bugs vanish with no trace | At minimum log or print e.getMessage(); never leave a catch block empty |
Treating e.getMessage() as the whole story |
It's only the first line; it skips the call chain | Read the full stack trace when debugging, not just the message |
Putting code that must always run only in the try block |
It is skipped entirely if an exception is thrown first | Put "always run" code in finally |
Writing catch (NumberFormatException e) but never checking the value (range, length) |
A technically valid number can still be a wrong PIN or a negative amount | Validate the value too, with your own exception if needed |
Making every custom exception extend Exception directly |
Forces every caller to catch or declare it, even for simple "bad input" cases | Extend RuntimeException for input-validation exceptions, unless you have a specific reason to force handling |
| Assuming an uncaught exception just prints a warning | It stops the program immediately, at that exact line | Catch anything you expect could realistically happen, especially around user input |
| Reading only the top JDK-internal stack frame | java.base/... frames are rarely where your bug is |
Scan down to the first frame naming one of your own .java files |
Quick recap
- An uncaught exception prints a stack trace and stops the program immediately, exit code
1. try/catchrecovers from an exception instead of crashing;finallyalways runs after, success or failure, even through areturn.- List
catchblocks most specific first; combine unrelated types withcatch (A | B e)when they're handled the same way. - Unchecked exceptions (
RuntimeExceptionand subtypes) compile with nocatchrequired; checked exceptions (everything else underException) force you tocatchorthrowsat compile time. - Write your own exception by extending
RuntimeException(usually) and callingsuper(message); throw it withthrow new YourException(...). - Read a stack trace top to bottom: exception + message first, then the call chain, most recent call first; look for the first frame that names your own file.
Checklist
- I can explain what the JVM does with an uncaught exception, and read its stack trace.
- I can write a
try/catchthat recovers and lets the program keep running. - I can order several
catchblocks correctly, and combine two withcatch (A | B e). - I can say whether a given exception is checked or unchecked, and why that changes what
javacrequires. - I can write and throw my own exception class, and catch it like a built-in one.
- I can build a retry loop around
Scannerinput that never crashes on bad input and gives up gracefully after too many attempts.