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.
// 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 kind | Describes | The language obliges | The response |
|---|---|---|---|
| First | Something that can happen | Yes | Handle or pass on |
| Second | A bug | No | Fix the code |
Example 1 — why the language obliges only the first
- It can happen even in perfect code.
- So one must decide what to do.
- The second is solved by a fix and not a catch.
Example 2 — why this solves the broad catch
- One catches only what is obliged.
- Bugs continue upward.
- And are discovered at once.