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.
try {
// risky code
} catch (error) {
// handle the error
} finally {
// always runs
}try {
const data = JSON.parse("not valid json");
console.log(data);
} catch (error) {
console.log("Something went wrong:", error.message);
} finally {
console.log("Done attempting to parse.");
}Try it Yourself »try {
null.someMethod();
} catch (error) {
console.log(error.name, "-", error.message);
}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.
Console