The path through try, catch and finally
Even though try and catch both return, finally runs before the value reaches the caller.
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.
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.)
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
Walk through what happens, step by step, when a line in a try block throws.
When should you catch an error, and when should you let it pass?
Why doesn't a try around setTimeout catch an error thrown in the callback, and how do you fix it?
What is finally for, and what goes wrong if you return from it?
Preview
Console
Nothing logged yet.Expected console output
try: reading {"age": 12}
try: parsed OK
finally: always runs
Result: 12
try: reading {age: 12}
catch: SyntaxError
finally: always runs
Result: null