Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Follow an Error Into catch

A save is only text, and text can get damaged. When Sam’s save was cut off partway through the first recipe, JSON.parse() threw an uncaught SyntaxError, main.js stopped at that line, and the list stayed empty.

In this video, you wrapped the load in try and catch and followed, line by line, where JavaScript goes. Here are the key points:

  • The try statement is for code that might throw. The risky lines go inside the braces of try. The catch block after them runs only if something inside try throws. The name in the parentheses of catch, such as error, holds the error that was thrown. Its name property is the error’s type, such as "SyntaxError" for bad JSON.
  • When a line in try throws, JavaScript leaves try at that line and jumps straight to catch. With the damaged save, the Console showed parsing the save, caught a SyntaxError and 5 recipes loaded, but never parsed it. The throw came before the assignment, so recipes still held the starter recipes, and the page showed those five with no uncaught error.
  • When catch finishes, JavaScript carries on after the whole statement. Watch out: catch never sends JavaScript back into try. Anything that must still happen goes after the statement, or, if try or catch returns, in finally.
  • When nothing throws, every line in try runs and catch is skipped. With a good save, the Console showed parsing the save, parsed it and 6 recipes loaded.
  • A finally block comes last and runs after try or after catch, whichever path JavaScript took. It runs even when try or catch returns. A line after the statement inside the function never would, so work for both paths goes in finally.
  • A return in try or catch waits for finally, then leaves the function. The return still picks the value the function hands back, but the function doesn’t finish until finally has run. Any lines after the statement inside the function are skipped.
  • Both paths logged load finished before the recipe count. With a good save, loadRecipes() logged parsed it and load finished before the line after the call logged 6 recipes loaded. With the damaged save, it logged caught a SyntaxError, load finished and 5 recipes loaded.

Here’s the loading code from the end of the video, in recipes/main.js under starterRecipes. The labeled logs are only there to show which lines run:

Language: JavaScript Filename: recipes/main.js
function loadRecipes() {
  const savedText = localStorage.getItem("recipe-box");
  try {
    const saved = JSON.parse(savedText);
    console.log("parsed it");
    return saved ?? starterRecipes;
  } catch (error) {
    console.log(`caught a ${error.name}`);
    return starterRecipes;
  } finally {
    console.log("load finished");
  }
}

const recipes = loadRecipes();
console.log(`${recipes.length} recipes loaded`);

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

00:00 Sam’s recipe box now loads its save on every visit. But a save is only text, and text can get damaged. In this video, you’ll follow, line by line, what JavaScript does when reading a save goes wrong.

00:15 To fake a damaged save, open the Application panel, double-click the recipe box value, and cut it off partway through the first recipe. Then reload. The list is empty, and the Console shows an uncaught SyntaxError.

00:30 JSON.parse threw on the cut-off text. Nothing caught the error, so main.js stopped at that line, and the code that draws the list never ran.

00:41 For code that might throw, JavaScript has the try statement. The risky lines go inside try’s braces. After them comes a catch block, which runs only if something inside try throws.

00:54 The name in catch’s parentheses, here error, holds the error that was thrown. Its name property is the error’s type, such as SyntaxError for bad JSON.

01:06 Here’s the load from main.js with try and catch around it. The recipes variable now starts as the starter recipes, with let, so the try block can replace them.

01:17 Four labeled logs will show which lines run. There’s one before the parse, one after it, one in catch, and one after the whole statement.

01:27 Save main.js, and the page reloads with the damaged save still stored. JavaScript starts at the top of try. The parsing the save log appears, then JSON.parse runs and throws.

01:40 Your turn: pause the video and predict whether the parsed it log appears. It doesn’t. The moment JSON.parse throws, JavaScript leaves try and jumps straight to catch.

01:54 Its log, caught a SyntaxError, appears next. When catch finishes, JavaScript carries on after the whole statement, and the recipes loaded log shows five. The throw came before the assignment, so recipes still holds the starter recipes.

02:11 The page shows those five, and there’s no uncaught error. Watch out: catch never sends JavaScript back into try. Anything that must still happen goes after the statement, or, if try or catch returns, in finally, coming up soon.

02:29 Now the other path. Sam adds the pea and mint soup again, and saveRecipes saves over the damaged text. Reload. JSON.parse succeeds, so every line in try runs, and the Console shows parsing the save, then parsed it.

02:46 Nothing threw, so JavaScript skips catch, and the recipes loaded log shows six.

02:53 Often, loading lives in a function that hands back the recipes. Here’s one, loadRecipes. Its try block returns the parsed save, and its catch block returns the starter recipes.

03:04 A third block, finally, comes last. It runs after try or after catch, whichever ran. Save main.js, and the page reloads. The save is good now, so try gets as far as its return.

03:19 Your turn: pause the video and predict where the load finished log lands: before the recipes loaded log, after it, or not at all.

03:29 Before. The return in try picks the value to hand back, but the function doesn’t finish yet. JavaScript runs finally first, which logs load finished. Only then does it hand back the recipes, and the recipes loaded log, after the call, shows six.

03:46 With the damaged save, catch’s return waits the same way.

03:53 Here, finally only logs, to show when it runs. Try and catch both return, so a line after the statement, inside loadRecipes, would never run. Work for both paths goes in finally.

04:07 As a rule: when a line in try throws, JavaScript skips the rest of try, runs catch, then finally, and carries on after the statement. But a return in try or catch waits for finally, then leaves the function instead.

04:23 Sam’s box now survives a damaged save. But this catch catches every error, including ones it can’t handle. Next, in Catch Only What You Can Handle, you’ll narrow it down.

Become a Member to join the conversation.