Skip to content
AgileLogics
4 min read

Basic Error Handling

Prerequisites: Functions

An error that happens while a program is running is called an exception. try/catch lets you catch one and respond instead of letting the whole program crash.

try {
    const data = JSON.parse("not valid json");
} catch (error) {
    console.log("That wasn't valid JSON:", error.message);
}

JavaScript tries the try block first; if an error is thrown inside it, execution jumps straight to catch instead of crashing.

Common mistakes

  • Wrapping code in try/catch and then doing nothing in catch, silently hiding bugs you'd want to know about. At minimum, log the error.