Errors in software applications are inevitable—from unexpected user inputs to malformed JSON payloads and network failures. Rather than letting unhandled exceptions crash your entire application, the try...catch statement allows developers to intercept runtime errors and recover gracefully.
When an exception occurs, JavaScript instantiates an Error object passed to the catch block with three primary properties:
error.name: The error classification type (e.g., ReferenceError, TypeError, SyntaxError).error.message: A human-readable description of what went wrong.error.stack: A detailed stack trace of function calls indicating the exact file and line number.| Error Type | Triggered When... | Example |
|---|---|---|
TypeError | Operation executed on inappropriate type | null.toUpperCase() |
ReferenceError | Accessing an undeclared variable | console.log(foo) |
SyntaxError | Invalid JavaScript or malformed JSON | JSON.parse('{bad_json}') |
RangeError | Numeric value falls outside allowable range | new Array(-1) |
URIError | Malformed URI passed to decodeURIComponent() | decodeURIComponent('%') |
In earlier versions of JavaScript, you were required to declare an error parameter: catch (e). In ES2019+, if the error details are not needed, you can omit the parameter completely:
A classic pitfall: try...catch is synchronous. It cannot catch errors thrown inside asynchronous callbacks (like setTimeout or event listeners) because the try block finishes executing before the callback is fired!
(Note: To catch errors in asynchronous code, use .catch() on Promises or wrap await expressions inside try...catch).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Mini Project: Random Joke Generator | finally block |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.