Grade 12 Computer Science · Exceptions and testing

Exceptions in a language that checks

Two kinds, and the language treats them differently.

A missing file is required, a bad position is not

Java refuses to compile code that reads a file without your saying what happens if the file does not exist. But it happily compiles code that reaches the tenth cell of a three-cell array. It looks inconsistent. What if it is exactly the right decision?

In grade ten you learned to treat failure as a path one plans, and the three responses — handle, pass on, convert. All that is true. What is added here is that the language distinguishes two kinds of failure, and obliges you to address only one of them.

Three kinds of input, and only checking all three says something.
// first kind: must be handled or declared
static String read(String path) throws IOException {
    return Files.readString(Path.of(path));
}

// second kind: a bug. Do not catch it — fix the caller.
static int at(int[] a, int i) {
    return a[i];        // out of range means the caller erred
}

What this changes in practice

This distinction solves exactly the problem we warned of in grade ten: a broad catch that swallows bugs too. If one catches only the first kind, bugs continue upward and are discovered — and that is exactly what is wanted. The practical rule becomes very simple: catch what the language obliges, and do not catch what it does not. And in the few cases where one does catch the second kind — for instance at a system’s boundary, to return an orderly message instead of crashing — one does so explicitly and in one place.

The kindDescribesThe language obligesThe response
FirstSomething that can happenYesHandle or pass on
SecondA bugNoFix the code

Example 1 — why the language obliges only the first

  1. It can happen even in perfect code.
  2. So one must decide what to do.
  3. The second is solved by a fix and not a catch.

Example 2 — why this solves the broad catch

  1. One catches only what is obliged.
  2. Bugs continue upward.
  3. And are discovered at once.
Catch what the language obliges, and do not catch what it does not.