Bitpath

Lesson 2 · Unit 06

Errors and modules

Catch what goes wrong at run time, and split a program across files

13 exercisesabout 3 min

What you practise

  • try, catch and the unknown you caught, throw, a result type instead of an exception, export and import, JSON.parse and why its result needs checking

Try a question from this lesson

Pick one

JSON.parse turns text into data, and fails when the text is not valid. This compiles. What happens when it runs?

TypeScript
console.log("start");
const user = JSON.parse("oops");
console.log("end");

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

try and catch

Put the risky lines in a try block. If one of them throws, the rest of the try block is skipped and the catch block runs instead.

If nothing throws, the catch block is skipped. Either way, the program carries on after it.

TypeScript
try {
  JSON.parse("oops");
  console.log("parsed");
} catch (err) {
  console.log("bad text");
}
console.log("still running");

// bad text
// still running

Concept

A result instead of a throw

Nothing in a function's type says that it may throw, so nothing makes the caller catch.

A result type puts failure in the return value: a union with an ok property that tells the two shapes apart, as kind did. The caller must check ok before the compiler allows value.

TypeScript
type Result =
  | { ok: true; value: number }
  | { ok: false; error: string };

function toAge(text: string): Result {
  const n = Number(text);
  if (Number.isNaN(n)) {
    return { ok: false, error: "bad" };
  }
  return { ok: true, value: n };
}

Concept

Modules

Programs grow past one file. Each file is a module with its own names: nothing gets out by accident.

export in front of a function, a const or a type offers it to other files. They take it with import { name } from "./file". Everything not exported stays private to its file.

TypeScript
// file: prices.ts
export function withTax(n: number) {
  return n + n / 5;
}
const secret = 7; // not exported

// file: main.ts
import { withTax } from "./prices";
console.log(withTax(10)); // 12

9 more exercises in the app

  • 2× type the answer
  • 4× multiple choice
  • 1× fill the blanks
  • 1× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy