

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 7
click for more info
Not enough gems
Cost: 6 gems
1: Error Handling in TypeScript
incomplete
2: Bugs vs. Errors
incomplete
3: Async/Await Makes Error Handling Easier
incomplete
This lesson's interactive features are locked, please to keep using them
When something goes wrong while a program is running, TypeScript uses the try/catch paradigm for handling those errors. Try/catch is fairly common, Python uses a similar mechanism.
For example, let's say we try to access a property on an undefined variable. JavaScript will automatically "throw" an error.
const speed = car.speed;
// The code crashes with the following error:
// "ReferenceError: car is not defined"
By wrapping that code in a try/catch block, we can handle the case where car is not yet defined. In TypeScript, the catch block parameter is typed as unknown by default, so you need to check if the error is an instance of Error before accessing its properties, like message. This ensures type safety and prevents runtime errors when the error is not an Error object.
try {
const speed = car.speed;
} catch (err: unknown) {
if (err instanceof Error) {
console.log(`An error was thrown: ${err}`);
// the code cleanly logs:
// "An error was thrown: ReferenceError: car is not defined"
} else {
console.log("An unknown error occurred:", err);
}
}
When an error is thrown, execution skips the rest of the try block and jumps to catch.
When handling a thrown Error object, you must access the message property of the error object to display it correctly to the console.
try {
// computation
throw new Error("This is the error message");
} catch (err) {
if (err instanceof Error) {
console.log(`An error was thrown: ${err.message}`);
// the code cleanly logs:
// "An error was thrown: This is the error message"
}
}
The following code is failing to execute. It is throwing an error string that isn't being handled gracefully. As a result, the entire program is crashing.
Properly handle the error in the code by wrapping all of the function calls within a single try...catch block. The catch block should log the error's message property to the console without extra formatting.