All tutorials
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
done

4. 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

  1. Throw a custom error when input is not a number
  2. Catch a JSON.parse failure
  3. Wrap an async function in try/catch and log the error
→ Try more practice problems