Skip to main content

JavaScript try catch — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript try catch lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.

Exercises(5)

  1. 1

    Handle bad JSON

    easy10 min

    Catch the parse failure and report a message.

  2. 2

    Parse valid JSON

    easy10 min

    Parse good JSON and report the name from it.

  3. 3

    Declare the variable outside

    easy10 min

    Keep the value usable after the try block.

  4. 4

    Catch without the parameter

    easy10 min

    Use a catch block that does not name the error.

  5. 5

    Record why it failed

    medium10 min

    Report the error name rather than swallowing it.

Find the bug(5)

  1. 1

    Fix the variable declared inside

    easy8 min

    A variable declared in the try block cannot be read outside it.

  2. 2

    Fix the empty catch

    easy8 min

    Swallowing the error silently hides what happened.

  3. 3

    Fix the try block wrapped too widely

    easy8 min

    Only the parse can fail, so only it belongs inside.

  4. 4

    Fix the catch that reruns the failure

    easy8 min

    Repeating the failing call inside catch throws again.

  5. 5

    Fix the result read before assignment

    easy8 min

    The value is used before the try block has set it.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace