Why exceptions are not for normal flow
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Exceptions are for situations that are truly out of the ordinary: a missing file, a dropped connection, a bug. Using them to steer everyday logic, such as ending a loop or testing whether text is a number, makes code slower, harder to read, and better at hiding real bugs.
What creating an exception costs: the stack trace capture
When an exception object is created, its constructor calls fillInStackTrace(), which walks the current call stack and records every frame. That record is what printStackTrace() shows later, and it is the expensive part of an exception.
Example 1 · The trace grows with the call depth
public class TraceDepthDemo { static int traceLength(int depth) { if (depth == 1) { Exception e = new Exception("created, never thrown"); return e.getStackTrace().length; } return traceLength(depth - 1); }
public static void main(String[] args) { int[] depths = {1, 10, 100, 1000}; for (int depth : depths) { System.out.println("depth " + depth + ": " + traceLength(depth) + " frames recorded"); } }}depth 1: 2 frames recorded depth 10: 11 frames recorded depth 100: 101 frames recorded depth 1000: 1001 frames recorded
What this code does
- The exception is never thrown, yet
getStackTrace()already holds every frame: the constructor captured them all atnew. - Each extra level of calls adds one frame to record (plus one for
main). Creating exceptions deep inside a busy program costs more than in a small test.
The cost is paid at new, not at throw: an exception that is created and never thrown still captures its trace. The deeper the call stack, the more frames there are to record, and real applications often run 50 to 100 calls deep. As a simplified model, think of a normal if as costing nanoseconds and a created, thrown and caught exception as costing hundreds to thousands of times more. For one failure a day this does not matter at all. For a check that runs a million times, it does.
(message, cause, enableSuppression, writableStackTrace) and false for the last argument. The trace is then empty, which makes debugging much harder, so this is for rare, measured cases only.Exceptions used as a goto: the anti-pattern
Using an exception as a goto means throwing or catching one just to jump out of normal code: ending a loop when an index runs past the end, or throwing a "found it" exception to escape nested loops.
Example 2 · Ending a loop with an exception hides a bug
public class GotoLoopDemo { // Anti-pattern: the exception means "loop finished" static int bestJumpExceptionStyle(int[] marks) { int best = 0; int i = 0; try { while (true) { best = Math.max(best, marks[i + 1] - marks[i]); i++; } } catch (ArrayIndexOutOfBoundsException e) { return best; } }
// The same anti-pattern with a typo: i + 2 instead of i + 1 static int bestJumpExceptionStyleTypo(int[] marks) { int best = 0; int i = 0; try { while (true) { best = Math.max(best, marks[i + 2] - marks[i]); i++; } } catch (ArrayIndexOutOfBoundsException e) { return best; } }
// A normal loop with the same typo static int bestJumpLoopTypo(int[] marks) { int best = 0; for (int i = 0; i + 1 < marks.length; i++) { best = Math.max(best, marks[i + 2] - marks[i]); } return best; }
public static void main(String[] args) { int[] unitTests = {42, 55, 61, 58, 80}; System.out.println("exception style: " + bestJumpExceptionStyle(unitTests)); System.out.println("exception style, typo: " + bestJumpExceptionStyleTypo(unitTests)); try { System.out.println("normal loop, typo: " + bestJumpLoopTypo(unitTests)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("normal loop, typo: fails at once: " + e.getMessage()); } }}exception style: 22 exception style, typo: 19 normal loop, typo: fails at once: Index 5 out of bounds for length 5
What this code does
- The first method is correct (the biggest jump between unit tests is 58 to 80, that is 22), but it ends only because an index finally fails, and the
catchquietly means "done". - With a typo, the exception-style method returns 19, a wrong answer with no warning, because the bug's exception looks exactly like "end of array". The normal loop with the same typo fails at once with the bad index, so the bug is found in minutes. (
maincatches it here only to print it.)
It works, but it lies to the reader. A catch (ArrayIndexOutOfBoundsException e) that means "the loop is finished" also catches a real indexing bug inside the loop, so the bug silently cuts the results short. Normal tools say what you mean: a loop condition, break, or return from a small method.
Check first versus try first
Check first means testing the input before using it: "is this text a number?" then parseInt. Try first means calling parseInt directly and catching NumberFormatException. Both are correct Java; the choice depends on how often the input is bad.
Example 3 · A complete check versus try first
public class CheckFirstDemo { // strict check: 1 to 9 digits always fits in an int static boolean isSmallNumber(String s) { if (s.isEmpty() || s.length() > 9) { return false; } for (int i = 0; i < s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { return false; } } return true; }
static String tryFirst(String s) { try { return "ok " + Integer.parseInt(s); } catch (NumberFormatException e) { return "not a number"; } }
static String checkFirst(String s) { return isSmallNumber(s) ? "ok " + Integer.parseInt(s) : "not a number"; }
public static void main(String[] args) { String[] fields = {"450", "45O", "", "99999999999", "007"}; for (String f : fields) { System.out.printf("%-14s try-first: %-13s check-first: %s%n", "\"" + f + "\"", tryFirst(f), checkFirst(f)); } }}"450" try-first: ok 450 check-first: ok 450 "45O" try-first: not a number check-first: not a number "" try-first: not a number check-first: not a number "99999999999" try-first: not a number check-first: not a number "007" try-first: ok 7 check-first: ok 7
What this code does
- Both styles agree on every input, including
"99999999999", which has only digits but is too big for anint. The length limit of 9 is what makes the check complete. Character.isDigitalso accepts digits from other scripts, such as Devanagari, whichparseIntalso understands, so the two stay in step. A simplerc >= '0' && c <= '9'test would also be correct here.
Example 4 · Measuring both styles on bad input
public class CostDemo { static boolean isSmallNumber(String s) { if (s.isEmpty() || s.length() > 9) { return false; } for (int i = 0; i < s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { return false; } } return true; }
static int countTryFirst(String[] inputs) { int valid = 0; int invalid = 0; for (String s : inputs) { try { Integer.parseInt(s); valid++; } catch (NumberFormatException e) { invalid++; } } return valid; }
static int countCheckFirst(String[] inputs) { int valid = 0; for (String s : inputs) { if (isSmallNumber(s)) { Integer.parseInt(s); valid++; } } return valid; }
public static void main(String[] args) { String[] inputs = new String[200_000]; for (int i = 0; i < inputs.length; i++) { inputs[i] = (i % 2 == 0) ? String.valueOf(i) : "roll-" + i; // half are bad } for (int round = 1; round <= 3; round++) { long t1 = System.nanoTime(); int a = countTryFirst(inputs); long t2 = System.nanoTime(); int b = countCheckFirst(inputs); long t3 = System.nanoTime(); System.out.printf("round %d: try-first %d valid in %d ms, check-first %d valid in %d ms%n", round, a, (t2 - t1) / 1_000_000, b, (t3 - t2) / 1_000_000); } }}round 1: try-first 100000 valid in 189 ms, check-first 100000 valid in 14 ms round 2: try-first 100000 valid in 167 ms, check-first 100000 valid in 19 ms round 3: try-first 100000 valid in 174 ms, check-first 100000 valid in 13 ms
What this code does
- Both methods find the same 100000 valid numbers. The try-first version also creates 100000
NumberFormatExceptionobjects, each with its stack trace, and that is where its extra time goes. - Your times will differ by computer and Java version, and the first round is slower while the JVM warms up. The pattern to notice is the large gap between the two, not the exact numbers.
When bad input is common, such as scanning a file where half the fields are not numbers, check first: the cheap test avoids creating thousands of exceptions. When bad input is rare, such as one number typed by a user, try first is simpler and fast enough. A check must be complete to replace the try. An "only digits" test accepts "99999999999", which is too big for an int, so parseInt still throws. Either make the check strict, for example at most 9 digits, or keep the try as a safety net.
Optional or a result value as the alternative
When "not found" or "not valid" is a normal answer, return it as a value instead of throwing. Optional<T> says "there may be no value" right in the method's return type, and the caller must deal with it before using the value.
Example 5 · Optional and a result record instead of exceptions
import java.util.List;import java.util.Map;import java.util.Optional;
record ParseResult(Integer value, String error) { static ParseResult ok(int value) { return new ParseResult(value, null); }
static ParseResult fail(String error) { return new ParseResult(null, error); }
boolean isOk() { return error == null; }}
public class ResultValueDemo { static final Map<String, String> NAMES = Map.of("CS101", "Asha", "CS102", "Ravi");
// "not found" is normal here, so it is part of the return type static Optional<String> findName(String roll) { return Optional.ofNullable(NAMES.get(roll)); }
// the caller also wants to know why a value is bad static ParseResult parseMarks(String text) { if (text.isEmpty()) { return ParseResult.fail("marks are empty"); } for (char c : text.toCharArray()) { if (!Character.isDigit(c)) { return ParseResult.fail("not a number: " + text); } } if (text.length() > 3 || Integer.parseInt(text) > 100) { return ParseResult.fail("more than 100: " + text); } return ParseResult.ok(Integer.parseInt(text)); }
public static void main(String[] args) { System.out.println(findName("CS101").orElse("unknown roll")); System.out.println(findName("CS999").orElse("unknown roll"));
for (String text : List.of("88", "8B", "", "120")) { ParseResult r = parseMarks(text); System.out.println(r.isOk() ? "marks " + r.value() : "rejected: " + r.error()); } }}Asha unknown roll marks 88 rejected: not a number: 8B rejected: marks are empty rejected: more than 100: 120
What this code does
findNamereturnsOptional<String>, so the type itself tells callers that a roll may be unknown, andorElsehandles it in one call, with notry.ParseResultcarries either a value or an error message. Rejecting bad marks is a normal answer here, so no exception is created at all.
When the caller also needs the reason, return a small result record, such as ParseResult(Integer value, String error), with one field for success and one for the error message. Keep exceptions for the cases where continuing normally makes no sense.
Next step
Check your understanding
12 quick questions