JavaScript lesson · 18 min

JavaScript Errors and try/catch

Handle expected failures with try/catch instead of letting the whole script crash.

Code runs locally in your browser

What you will practice

  • Recognize that errors are part of normal programming.
  • Use try/catch around code that may fail.
  • Show a useful fallback message.

What this means

An error means JavaScript could not complete an operation. Some errors are programmer mistakes, while others are expected problems, like invalid JSON or missing data.

`try` marks the code that might fail. `catch` receives the error and lets you decide what to do next.

Catching an error should not hide every problem silently. A good catch block gives the user, log, or developer a useful message.

If this is your first time seeing this

Errors are not a sign that programming is going badly. They are how the program tells you something needs attention.

try/catch is for expected failures where you can recover or show a useful message.

Mini glossary

Error
A problem that prevents an operation from completing.
try
A block where you put code that might fail.
catch
A block that runs when the try block throws an error.

Example from everyday life

try/catch is like opening a package that might be damaged. You try to open it normally. If something is wrong, you do not pretend everything is fine; you switch to a recovery plan and explain what happened.

How it works step by step

  1. The code starts with broken JSON text.
  2. `JSON.parse` throws an error because the text is not valid JSON.
  3. The `catch` block receives that error and stores a friendly message.
  4. The program continues running and prints the fallback message instead of stopping completely.

Where you will use this

  • A JSON formatter catches parsing errors and shows where the input is invalid.
  • A settings screen catches a storage error and falls back to default settings.
  • An API client catches a failed request and shows a retry message.

Before you run the code

Use try/catch around operations where failure is reasonable and recoverable.

Do not wrap your whole program in one giant catch block. Small, focused error handling is easier to understand.

Common beginner mistakes

  • Catching every error and ignoring it silently.
  • Showing raw technical errors directly to users.
  • Using try/catch to hide bugs instead of fixing them.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingShows a friendly parsing error
WaitingContinues after the caught error

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Fix the JSON string and see the success message.
  • Print `error.message` inside the catch block.
  • Change the fallback message to something a real user would understand.