Lesson 2 · Unit 06
Errors and modules
Catch what goes wrong at run time, and split a program across files
What you practise
try,catchand theunknownyou caught,throw, a result type instead of an exception,exportandimport,JSON.parseand 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?
console.log("start");
const user = JSON.parse("oops");
console.log("end");Correct answer
It prints start, then stops with an error
Why
The compiler cannot know what text will arrive, so this failure happens at run time. The error is thrown on line 2 and the program stops right there: line 3 never runs. Unless something catches it.
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.
try {
JSON.parse("oops");
console.log("parsed");
} catch (err) {
console.log("bad text");
}
console.log("still running");
// bad text
// still runningConcept
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.
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.
// 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)); // 129 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.