Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.2 — try, catch and finally
JavaScript · Example 3 of 4

try only sees errors while its block runs

The outer catch never runs: by the time the timers fire, that try finished long ago.

try runs code that might fail, catch runs only if it throws and receives the error, and finally runs in every case; catch an error only where you can do something useful with it, and rethrow the ones you can't handle.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write toNumber(text) that returns Number(text) when the result is a real number, and otherwise logs Not a number: <text> and returns 0. (Number doesn't throw, so decide whether you need try at all.)

02

Write parseOr(text, fallback) that returns JSON.parse(text) or fallback when the text isn't valid JSON, and rethrows any other kind of error. Test it with '[1,2]' and 'oops'.

Explain it without notes

01

Walk through what happens, step by step, when a line in a try block throws.

02

When should you catch an error, and when should you let it pass?

03

Why doesn't a try around setTimeout catch an error thrown in the callback, and how do you fix it?

04

What is finally for, and what goes wrong if you return from it?

try only sees errors while its block runs

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

try block finished
await inside try caught: server said no
Uncaught Error: thrown from a timer
try inside the callback caught: SyntaxError