Advanced
Error Handling
try / catch / finally and custom Error classes.
1. Explanation
Wrap risky code in try { } and handle failures in catch (err). finally always runs. Throw your own errors with throw new Error('message'). Errors have name, message and stack. For async code, await inside try/catch.
2. Example
Try it yourself
Console
Click Run to see output.
3. Expected output
output
5
Error: Cannot divide by zero
done4. Common mistakes
- ✗Swallowing errors with an empty catch block
- ✗Throwing strings instead of Error objects (no stack trace)
- ✗Forgetting to await inside try — the rejection escapes the catch
5. Practice questions
- Throw a custom error when input is not a number
- Catch a JSON.parse failure
- Wrap an async function in try/catch and log the error