JavaScript Tutorial: Error Handling
try/catch/finally, throw, custom error types, and building resilient code that fails gracefully.
Things go wrong — handle it
Every real-world program encounters unexpected situations: network timeouts, invalid input, missing data, API errors. Without error handling, your program just crashes.
JavaScript gives you `try/catch/finally` and a hierarchy of built-in error types. Learning to throw and catch the right error makes debugging 10× faster.
What you'll learn in this JavaScript error handling tutorial
This interactive JavaScript tutorial has 8 hands-on exercises. Estimated time: 18 minutes.
- try/catch — contain the crash — Without try/catch, an error stops your program dead. With it, you handle the problem and keep going.
- The Error object — When an error is caught, you get an `Error` object with:
- Built-in error types — JavaScript has 7 built-in error types — each for a different category:
- throw — trigger your own errors — `throw` lets you trigger an error yourself — to signal invalid input or impossible state.
- Custom error classes — Extend `Error` to create your own error types — makes it easy to catch and handle your application's specific errors.
- finally — always runs — `finally` runs whether or not an error occurred — perfect for cleanup:
- Re-throw — only handle what you know — A catch block should only handle errors it understands. Re-throw anything else:
- Build a safe API call wrapper — Final challenge — no starter code.
JavaScript Error Handling concepts covered
- Things go wrong — handle it