Error Handling
Why Errors Happen (And Why That's OK)
Errors are a normal part of programming. A user types something unexpected. A server goes down. A file doesn't exist. Good code doesn't prevent all errors — it handles them gracefully.
Think of error handling like a safety net under a trapeze. The acrobat (your code) does amazing things up high, and the net (error handling) catches them if they fall. Without it, one mistake crashes the whole show.
JavaScript has several built-in error types:
TypeError— doing something a value's type doesn't support (like callingnull.toString())ReferenceError— using a variable that doesn't existSyntaxError— writing code JavaScript can't parseRangeError— a number outside the allowed rangeURIError— bad URI encoding
Try / Catch / Finally
Throwing Your Own Errors
You're not limited to catching JavaScript's built-in errors — you can throw your own. Use throw to signal that something went wrong in your code. This is like pulling the fire alarm when you spot a problem.
You can throw anything (a string, a number), but best practice is to throw an Error object because it includes a stack trace — a breadcrumb trail showing exactly where the error came from.
Custom Errors & Validation
Error Handling Patterns
In real-world code, you'll often see these patterns:
- Catch and recover — handle the error and continue with a fallback
- Catch and log — log the error for debugging but let the app continue
- Catch and re-throw — catch specific errors you can handle, re-throw the rest
- Guard clauses — check for problems early with
ifstatements before they become errors
A good rule of thumb: use try/catch around code that interacts with the outside world — network requests, file operations, JSON parsing, user input. For your own logic, prefer guard clauses and validation.
Real-World Pattern: Safe JSON Parsing
Quick check
Continue reading