When Things Go Wrong: try...catch

Learn how to gracefully handle errors so your program recovers instead of crashing.

Step 1 of 5

Programs break — and that's okay

No matter how carefully you write code, errors happen. A user types letters where a number is expected. A network request fails because the WiFi dropped. A JSON file has a missing comma. These are not bugs in your code — they're normal situations that your code needs to handle.

Without error handling, a single error crashes your entire program. The browser shows a cryptic message in the console, and nothing else runs. That's a terrible experience for users — imagine if Google crashed every time a search request timed out!

JavaScript gives you `try...catch` to deal with errors gracefully: try something risky, and if it fails, catch the error and handle it instead of crashing.

Think of it this way: try...catch is like a safety net under a tightrope walker. You try the risky move, and if you fall, the catch block catches you instead of crashing to the ground. The show goes on — the audience might not even notice anything went wrong.
Web Standard
Error handling with try...catch has been in JavaScript since ES3 (1999). The Error object and its subtypes (TypeError, SyntaxError, RangeError, etc.) are defined by the ECMAScript specification. Every JavaScript engine throws the same types of errors in the same situations.
Learn more on MDN