Lesson 52 +15 XP

Try and Catch

Try and Catch

try and catch let you handle errors gracefully instead of letting them crash your code.

The basic structure

try {
  // code that might fail
} catch (err) {
  // code that runs if an error happens
}

Example

try {
  undefinedFunction();
} catch (err) {
  console.log("Caught: " + err.message);
}
console.log("Program keeps running");

The error is caught, and the program continues instead of crashing.

The error parameter

The catch block receives the error object, usually named err or e. Use err.message for the message.

The finally block

finally runs whether there is an error or not:

try {
  // risky code
} catch (err) {
  // handle error
} finally {
  // always runs
}

Great for cleanup, like closing files or hiding spinners.

Throw to create errors

Pair throw with try/catch to handle your own error conditions.

TL;DR

  • try runs risky code.
  • catch handles any error that occurs.
  • finally always runs, with or without errors.
  • err.message gives the error description.