30 min·intermediate

Lesson 5

Errors & try/catch

Build a practical mental model for errors & try/catch and use it in working JavaScript.

By the end, you will be able to…

  • Explain errors & try/catch in your own words
  • Use errors & try/catch in a small program
  • Recognize and debug a common failure mode

Build the mental model

try/catch runs code that might throw, and recovers instead of crashing the whole program if it does. Around async code, it catches both synchronous throws and rejected awaited Promises.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Returns parsed JSON, or null with a logged message on failure

Why this matters

Unhandled errors crash scripts and leave users staring at a broken UI; deliberate error handling lets you show a helpful message instead.

Real-world example

Every 'Something went wrong, try again' UI state you've seen is a caught error rendered as a fallback instead of a blank crash.

Common mistakes

  • Wrapping code in try/catch but doing nothing useful in the catch block
  • Forgetting fetch() does not reject on HTTP error statuses like 404 — you must check response.ok yourself
  • Swallowing errors silently instead of logging or surfacing them

Try it yourself

Challenge

Write safeDivide(a, b) that throws on division by zero and returns null when caught.

Practice

Knowledge check

Does fetch() reject its Promise when the server responds with a 404?

Summary

Use try/catch to recover from thrown errors and rejected awaits, and always check response.ok explicitly with fetch.