try...catch
try...catch in Modern JavaScript
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.
1. Syntax & Core Flow
2. The Error Object
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.
3. Standard Built-in Error Types
| 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('%') |
4. Optional Catch Binding (ES2019)
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:
5. Limitations: try...catch CANNOT Catch Asynchronous Callback Errors!
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).
Practice Quiz
finally block
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Mini Project: Random Joke Generator | finally block |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.