Command Palette

Search for a command to run...

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

Catch what you expect, rethrow the rest

If loadTheme returned "LIGHT" for every error, the missing theme bug would hide forever.

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?

Catch what you expect, rethrow the rest

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

DARK
Bad JSON, using the default theme
LIGHT
The caller caught: TypeError: Cannot read properties of undefined (reading 'toUpperCase')