Errors
Throwing and catching
ts
function divide(a: float, b: float): float {
if (b == 0) {
throw new RangeError("division by zero");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (err) {
console.log(err.name + ": " + err.message);
} finally {
console.log("done");
}finally runs whether the try succeeds or throws. You can use try with only finally.
The error classes
Error is the base class. It has message, name and stack, a trace of where the error was created. The built-in subclasses are TypeError, RangeError, ReferenceError, SyntaxError and AggregateError.
You can make your own:
ts
class SaveError extends Error {
constructor(message: string, public slot: int) {
super(message);
}
}
try {
throw new SaveError("disk full", 2);
} catch (err) {
console.log(err.message);
}Typed catch clauses
Give the catch variable a type to catch only that kind of error. The first matching clause runs. An untyped clause catches everything, so put it last. If nothing matches, the error keeps going.
ts
function parseLevel(text: string): int {
if (text.length == 0) {
throw new TypeError("empty level number");
}
return Int(text);
}
try {
parseLevel("");
} catch (err: TypeError) {
console.log("type error: " + err.message);
} catch (err: RangeError) {
console.log("range error: " + err.message);
} catch (err) {
console.log("something else");
}Inline try
try in front of an expression gives null when it throws. Pair it with ?? for a fallback:
ts
const good: int | null = try Int("123");
const bad: int | null = try Int("abc");
const level: int = try Int("abc") ?? 1;
console.log(good, bad, level);defer
defer runs a statement when the current scope ends: normally, by return, or by an error. It is the tidy way to release something you opened:
ts
function work(): void {
console.log("open");
defer console.log("close");
console.log("working");
}
work();Several defer statements run in reverse order, last one first.
Errors in async code
When an async function throws, its promise rejects. Awaiting it throws the error at the await, so the same try and catch work. See Async, series and parallel.