try / catch
try runs code that might fail, and catch receives the error so your program can decide what to do instead of crashing.
A try block runs its lines in order. If one of them throws an error with throw (or a function like JSON.parse throws it for you), JavaScript jumps straight to the catch block. The remaining lines inside try do not run.
catch (error) receives whatever was thrown. In strict TypeScript that value is unknown, because anything can be thrown. Before using error.message you must check its type, for example with error instanceof Error. That check happens at runtime; the unknown type is gone when Node runs the code.
It is written this way so an expected failure, like invalid JSON, does not bring the whole program down. You will see it from lesson 01.09 on, and later around code that uses await.
try {
risky();
} catch (error) {
// handle it
}
Reach for it when: an operation can fail for reasons outside your control (bad input, network, files) and you want to respond to the failure instead of letting the program stop.
Examples
Common mistake
try {
JSON.parse("{");
} catch (error) {
console.log(error.message);
}Why: In strict mode `error` is `unknown`, and you cannot read `.message` from a value whose type you don't know.
How to write it: Check first: if (error instanceof Error) { console.log(error.message); }.
