Error handling (try/catch)

Computer Science · JavaScript

Question 1 of 10

0

    What does this JavaScript code log? let n = 2; try { if (n > 7) { throw new Error("too big"); } n = n * 2; } catch (e) { n = -1; } finally { n += 1; } console.log(n);

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Error handling (try/catch) explained

    Error handling lets a program respond to a problem, such as bad input or a failed operation, without crashing. JavaScript uses try, catch and finally blocks, and the throw statement creates the errors that catch receives.

    Code in the try block runs normally. If a statement throws, execution jumps to the catch block and the rest of the try block is skipped. The catch block receives the error object, which has properties such as name and message. The finally block runs whether or not an error happened, which suits cleanup such as hiding a loading message.

    try {
        JSON.parse("{bad");
        console.log("parsed");
    } catch (err) {
        console.log(err.name);
    } finally {
        console.log("done");
    }
    

    Use throw new Error("message") to signal your own problem. JSON.parse throws a SyntaxError for invalid JSON. Caveat: try only catches errors thrown while its code runs. Errors inside a later callback, or an unawaited rejected promise, pass through, so await promises inside the try block.

    Worked example

    JSON.parse("{bad") is not valid JSON, so it throws before the log of parsed runs. The catch block logs err.name, which is SyntaxError. The finally block then logs done. The output is two lines: SyntaxError and done.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this JavaScript code log?

      let n = 17; try { if (n > 11) { throw new Error("too big"); } n = n * 2; } catch (e) { n = -1; } finally { n += 1; } console.log(n);

    • Medium

      What does this JavaScript code log?

      function f() { try { return 13; } finally { return 57; } } console.log(f());

    • Hard

      What does this JavaScript code log?

      try { new Array(-8); } catch (e) { console.log(e.name); }

      • TypeError
      • SyntaxError
      • ReferenceError
      • RangeError