DevPath · Learn to code ESPTEN

Error handling

try, catch and finally

When something fails

Some operations can fail: reading data that does not exist, converting text to a number, dividing by zero in an invalid way... If you do not handle it, an error stops the program's execution. To handle it in a controlled way you use the try...catch block.

try {
  // code that may fail
  const data = JSON.parse("this is not JSON");
} catch (error) {
  // runs only if there was an error
  console.log("Something went wrong:", error.message);
}

The finally block

It is optional and runs always, whether there was an error or not. It is used for cleanup tasks (closing connections, hiding a loading indicator...):

try {
  doSomething();
} catch (error) {
  console.log("Error:", error.message);
} finally {
  console.log("This runs no matter what");
}

Examples

Catch an error and continue

function parse(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.log("Invalid JSON:", error.message);
    return null;
  }
}
console.log(parse('{"ok":true}'));
console.log(parse("not json"));
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Throwing errors with throw →