try...catch0%

try...catch

Beginner12 min read•Updated: Jul 11, 2026
Study Materials

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

JavaScript
try {
// Code that may throw an exception
const data = JSON.parse(rawString);
processData(data);
} catch (error) {
// Executes ONLY if an exception is thrown inside the try block
console.error('Failed to parse data:', error.message);
}
Output
try Block Executing
│
Did an error occur?
┌─────────┴─────────┐
YES NO
│ │
▼ ▼
catch (err) Execution continues
│ normally after try
▼
Execution resumes

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.
JavaScript
try {
const result = undefinedVariable + 10;
} catch (err) {
console.log('Error Name:', err.name); // 'ReferenceError'
console.log('Error Message:', err.message); // 'undefinedVariable is not defined'
console.log('Stack Trace:', err.stack);
}

3. Standard Built-in Error Types

Error TypeTriggered When...Example
TypeErrorOperation executed on inappropriate typenull.toUpperCase()
ReferenceErrorAccessing an undeclared variableconsole.log(foo)
SyntaxErrorInvalid JavaScript or malformed JSONJSON.parse('{bad_json}')
RangeErrorNumeric value falls outside allowable rangenew Array(-1)
URIErrorMalformed 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:

JavaScript
// Modern concise syntax:
try {
return JSON.parse(cachedData);
} catch {
// Error variable omitted because we only care that it failed
return null;
}

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!

JavaScript
// FAILS TO CATCH!
try {
setTimeout(() => {
throw new Error('Boom!'); // CRASHES! try block has already completed!
}, 1000);
} catch (err) {
console.log('This will NEVER be reached!');
}

(Note: To catch errors in asynchronous code, use .catch() on Promises or wrap await expressions inside try...catch).


Interactive Quiz

Practice Quiz

Question 1
What happens when an error is thrown inside a try block?
Question 2
What type of error is thrown when calling a method on null or undefined (e.g., null.trim())?
Question 3
What feature introduced in ES2019 allows catch blocks to omit the error parameter?
Question 4
Why can a synchronous try...catch NOT catch an error thrown inside a setTimeout callback?
Question 5
Which property of an Error object provides the line-by-line sequence of function calls that led to the exception?
Next Lesson

finally block

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

PrevNext