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

Catching Only the Errors You Expect

Catching Only the Errors You Expect

The trustees’ report takes its title from Joan’s settings file, whose text sits in a variable to keep things short.

Her Python function, report_title(), parses the text and catches only json.JSONDecodeError, the error a hand edit with a stray comma causes. Every other exception passes straight through, so a bug still stops the script where Joan can see it. In this lesson, you ported that except line to JavaScript and found out what happens to the errors it doesn’t name:

Language: Python
import json

def report_title(text):
    try:
        settings = json.loads(text)
        return settings["report"]["title"]
    except json.JSONDecodeError:
        print("settings.json is not valid JSON")

text = '{"report": {"title": "October donations"}}'
print(report_title(text))

Run on October’s settings, Python prints October donations.

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:02 The trustees’ report takes its title from Joan’s settings file, whose text sits in a variable to keep things short. Her Python function parses that text and catches only json.JSONDecodeError, the error a hand edit with a stray comma causes.

00:19 Every other exception passes straight through, so a bug still stops the script where Joan can see it. In this lesson, you’ll port that except line to JavaScript, and find out what happens to the errors it doesn’t name.

00:33 Run on October’s settings, Python prints the report’s title.

00:39 In JavaScript, the port follows the Python line by line. JSON.parse() is built in, so there’s no import. The function becomes a function declaration, and try keeps its name.

00:54 The parse becomes JSON.parse(), and the title line swaps the brackets for dot access. Say that line gets a typo, reprot, standing in for any bug you didn’t plan for.

01:06 The settings text and the call port as they are. Next comes the except line. A JavaScript catch takes no type, so it becomes catch (err), which, much like except Exception as err, receives every error the try throws.

01:26 Watch out for naming the type in the header, as in catch (SyntaxError err): JavaScript stops with an unexpected identifier error before anything runs, because the parentheses take only a name.

01:41 So the type moves into the catch body, as an if statement. A JSON parse error is a SyntaxError, and instanceof asks, much like Python’s isinstance(), whether err is that kind of error.

01:55 For the stray comma, the check gives true, so the if runs. Unlike isinstance(), instanceof isn’t a function call: it’s an operator, written between the error and the class.

02:08 Inside it, the message line uses console.error(), so it goes to standard error.

02:17 Make the same typo in Python’s title line, and the script stops with a KeyError traceback. That’s the except line doing its job: it names one error, and lets this one out.

02:30 What does the JavaScript port log when you run it? Your turn: pause the video and predict.

02:41 It logs undefined, and nothing else. No error, no trace, and the script exits as if all went well.

02:52 settings.reprot is undefined: reading a missing property gives undefined, not an error. The error comes a step later, a TypeError as the code reads the title.

03:04 The catch caught it anyway. The instanceof check asked whether it was a SyntaxError, and the answer was no. So nothing inside the if ran, and the function fell off the end.

03:17 With no return, a function gives back undefined, like Python’s None, which the last line logged.

03:24 Python’s except picks the errors before it catches them. instanceof checks after the catch already has the error, so whatever you don’t handle there is gone.

03:38 The fix gives back Python’s behavior by hand. End the type check with an else block that holds throw err, which, like Python’s bare raise, throws the same error object on, with its trace.

03:52 Run it again, and the slip crashes with its TypeError, as the KeyError stopped Python’s version. The trace’s top frame points at the title line.

04:03 Fix the slip there, and both versions print October donations.

04:08 One catch takes every error, instanceof picks out the ones you expect, and a closing else throws the rest back. Then, as in Python, an unplanned bug crashes where you can see it.

04:22 Next up is Handling a Missing File, a text lesson. November’s export isn’t downloaded yet: you’ll find out how JavaScript tells a missing file apart.

Become a Member to join the conversation.