Grade 10 Computer Science · Errors as a designed path

Failure is an outcome, not an accident

Why every operation reaching outward needs two paths.

A bug no fix in the code will prevent

Your code is flawless, and still the file it reads was deleted, or the network went down halfway. There is no mistake to fix here, because it is not your mistake. So what exactly do you write, and who should decide what happens at that moment?

Until now an error was a sign that something was wrong in your code. There is a whole category of errors that is not that: a file that does not exist, a network that went down, input the user typed wrongly, a server that did not answer. No fix in the code will prevent them, because they are not your mistakes — they are simply the second outcome of an operation that has two.

Both exits always exist; only one of them is usually drawn.
def read_count(path):
    try:
        with open(path) as f:
            return int(f.read().strip())
    except FileNotFoundError:
        return 0                  # a sensible default
    except ValueError:
        raise ValueError(f"{path} does not hold a whole number")

The three possible answers

When an operation fails, there are exactly three sensible responses, and the difference between them is who knows what to do. Handle — when you know the right answer, like a sensible default. Pass on — when you do not know, and your caller probably does. Convert — when you know something the caller does not, and you add it to the message before passing on. There is no fourth response, and yet the commonest thing to see is a fifth: ignore.

The responseWhen
HandleWhen the right answer is known
Pass onWhen you do not know, and the caller does
ConvertWhen you have information the caller lacks

Example 1 — why two failures get two answers

  1. A missing file is a reasonable state.
  2. Zero is a sensible default.
  3. Content that is not a number is a fault.
  4. So it is passed on.

Example 2 — what happens without planning

  1. The operation fails at run time.
  2. The program stops midway.
  3. And leaves a partial state.
There is no fourth response. And ignoring it is not a response.