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 handling a thrown Error
object, you must access the message
property of the error object to display it correctly to the console.
let err = new Error("This is the error message");
try {
// computation
} 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 any error messages to the console, without extra formatting.
Focus Editor
Alt+Shift+]
Become a member to Submit
Become a member to Run
Become a member to view solution