JavaScript Fundamentals · Error Handling · Lesson 30 of 48
try, catch, and finally
Concept
try, catch, and finally
Wrapping risky code in a try block lets you catch errors gracefully instead of crashing the whole program. finally always runs, whether an error happened or not.
Only code inside the try block is protected — an error thrown asynchronously later, like inside a setTimeout callback, won't be caught by a try/catch wrapped around the setTimeout call itself.
- Explain the core idea behind try, catch, and finally.
- Predict output before running a change.
- Test one realistic and one unusual input.
- Use the result to make the next decision.
- 1. Read one concept.
- 2. Change the example.
- 3. Run, compare, and explain.
- 4. Complete the challenge below.
Self-check before continuing
Without looking at the example, describe what changes when you modify one input in try, catch, and finally. Then reopen the editor and prove your explanation with a small test.
You are ready to continue when you can predict, test, and explain the result.
Your turn
Wrap a line that intentionally throws (like calling a function that doesn't exist) in try/catch and log a friendly message instead of letting it crash.
Ask about this lesson or your next move. The guide explains the path without taking the work away from you.
Ready for the next lesson?
Mark this lesson complete when you have finished the exercise.
Console