Mary Knize

JavaScript error handling with try/catch

1 min read

Programming

My favorite way to describe a try/catch block in JavaScript:

If the computer can't do something, tell it to scream into a pillow and get over it.

Without a try/catch block, the missing key is going to throw an error:

const numbers = {
    one: {
        name: "one",
        number: 1
    },
    two: {
        name: "two",
        number: 2
    }
}

const keys = ["one", "two", "three"];

for (let k of keys) {
    console.log(numbers[k].number);
}

console.log("Going on with my day...");

The result is an ugly TypeError, and the program stops, never making it to "Going on with my day...".

$ node fail.js 
    1
    2
    /home/maryknize/Programming/Random/fail.js:15
        console.log(numbers[k].number);
                               ^

    TypeError: Cannot read property 'number' of undefined
        at Object.<anonymous> (/home/maryknize/Programming/Random/fail.js:15:28)
        at Module._compile (internal/modules/cjs/loader.js:1137:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
        at Module.load (internal/modules/cjs/loader.js:985:32)
        at Function.Module._load (internal/modules/cjs/loader.js:878:14)
        at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
        at internal/main/run_main_module.js:17:47

Now, with a try/catch block, the computer can catch the error, scream into a pillow, then continue on with the program.

const screamIntoAPillow = () => {
    console.log("I'm really upset that I can't do the thing!");
}

const numbers = {
    one: {
        name: "one",
        number: 1
    },
    two: {
        name: "two",
        number: 2
    }
}

const keys = ["one", "two", "three"];

for (let k of keys) {
    try {
        console.log(numbers[k].number);
    } catch(err) {
        screamIntoAPillow();
    }
}

console.log("Going on with my day...");
~                                        

And the result:

$ node try_catch.js 
    1
    2
    I'm really upset that I can't do the thing!
    Going on with my day...

Of couse, we can do much more than just scream into a pillow if there's an error. We can log the error, run a function that performs a different task, or just ignore it. The important thing is, the script will continue on instead of crashing in unpredictable ways.

Canonical URL