Catching Errors With try and catch

Joan’s report takes its title from settings.json, and a hand edit left a comma after the title: {"report": {"title": "October donations",}}. That isn’t valid JSON. Her Python script catches the json.JSONDecodeError from json.loads(). JavaScript’s JSON.parse() throws an error (JavaScript’s word for raises), and you’ll port the catch.

Catch a Broken Settings File

The JavaScript try statement keeps Python’s shape, with braces and new keywords:

Python JavaScript
try: try { ... }
except json.JSONDecodeError as err: catch (err) { ... }, any error
str(err) err.message
except json.JSONDecodeError: catch { ... }, any error
else: no equivalent
finally: finally { ... }

JavaScript has no typed except clauses, so a try gets at most one catch block, which receives every error thrown while the try runs. A try needs a catch, a finally, or both. Choosing which errors to handle, and the error object itself, come later.

The port reads the settings in a function so that its catch can return early:

Language: JavaScript
function showTitle(text) {
  let settings;
  try {
    settings = JSON.parse(text);
  } catch (err) {
    console.error(`settings.json is not valid JSON: ${err.message}`);
    return;
  }
  console.log(settings.report.title);
}

showTitle('{"report": {"title": "October donations"}}');
showTitle('{"report": {"title": "October donations",}}');

The function prints the title from the good file and reports an error for the broken one:

Language: Program Output
October donations
settings.json is not valid JSON: Expected double-quoted property name in JSON at position 41 (line 1 column 42)

Keep the try to One Call

Moving the title line into the try also works for a good file, but then the untyped catch handles errors from the title line too. For valid JSON with no report, such as {}, settings.report is undefined, so reading .title throws. The port prints settings.json is not valid JSON: Cannot read properties of undefined (reading 'title'), incorrectly blaming the JSON syntax.

Python guards against this in two ways: its typed except lets a KeyError propagate, and else keeps the title line outside the try. JavaScript has no typed catch and no else, so you build the second guard yourself by keeping the try to the one call that can fail. A const declared inside the braces wouldn’t exist outside them, unlike a name assigned in Python’s try, so showTitle() declares settings with let first.

The line after the try statement stands in for else, but only because the catch returns. Without that return, it would also run after a failure, with settings still undefined. A {} file stops showTitle() with an uncaught TypeError, as Python’s lookup would stop with an uncaught KeyError.

A } else { after the catch fails with SyntaxError: Unexpected token 'else' before anything runs, since try takes only catch and finally.

Drop the Name or Add finally

For a yes-or-no check, such as the test the food bank’s website volunteer runs on a hand edit before saving it, leave out the name and parentheses:

Language: JavaScript
function isValidJson(text) {
  try {
    JSON.parse(text);
    return true;
  } catch {
    return false;
  }
}

console.log(isValidJson("{}"));
console.log(isValidJson("{bad}"));

The first call returns true, and the second returns false from the catch:

Language: Program Output
true
false

A nameless catch still catches every error, so it suits a try whose only call that can fail is JSON.parse().

A finally block works exactly as in Python, running whether the try succeeds, throws, or returns:

Language: JavaScript
function readTitle() {
  try {
    return "from try";
  } finally {
    console.log("finally runs");
  }
}

console.log(readTitle());

JavaScript logs the finally line first, as Python would:

Language: Program Output
finally runs
from try

You’ll rarely need a finally block for files because readFile() opens and closes the file on its own when you give it a path. You’ll explore cleanup in more depth in a later lesson.

In JavaScript, one catch catches every error, so put in the try only what that catch is meant to handle: here, JSON.parse() and lines that can’t throw, like return true.

In the next lesson, Checking Instead of Catching, Joan’s script checks each donation against the donor’s pledge, and you’ll see why a try that does its job in Python can have nothing to catch in JavaScript.

Become a Member to join the conversation.