JS CodeLab
error handlingbeginner

JavaScript try...catch Error Handling Syntax Guide

•
Updated

Direct Answer & Overview

The JavaScript try...catch statement marks a block of statements to test for exceptions, with a designated handler block to execute if an error occurs. It prevents uncaught runtime exceptions from crashing applications and enables resilient recovery.

#try-catch#error-handling#exceptions#debugging

JavaScript Source Code

example.js
try {
  JSON.parse("invalid json");
} catch (error) {
  console.error("Failed to parse JSON");
  console.error(error);
}

How does this JavaScript code work?

Defensive JavaScript uses `try...catch` to isolate risky operations—such as parsing dynamic JSON strings, accessing network resources, or executing third-party code. If an exception is thrown inside the `try` block, normal execution halts immediately and control transfers to the `catch` block, which receives the thrown error object. An optional `finally` block can be added to execute cleanup logic regardless of success or failure.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
Failed to parse JSON
SyntaxError: Unexpected token 'i', "invalid json" is not valid JSON

Common mistakes to avoid

  • !Leaving catch blocks empty, silently swallowing errors and making system debugging impossible.
  • !Attempting to catch asynchronous errors from callbacks (e.g. setTimeout) with a synchronous try...catch; the exception is thrown outside the block.
  • !Wrapping entire applications in a single monolithic try...catch instead of handling failures close to their source.
  • !Catching errors without checking error types or re-throwing unexpected exceptions.

Frequently Asked Questions

Can try...catch catch asynchronous errors in JavaScript?

Synchronous try...catch cannot catch errors from asynchronous callbacks like setTimeout. However, it CAN catch errors from async/await when the promise rejects.

What is the purpose of the finally block?

The finally block always executes after try and catch have completed, regardless of whether an error was thrown or handled, making it ideal for resource cleanup.

Can you omit the error parameter in catch?

Yes. Since ES2019 (optional catch binding), you can write 'catch { ... }' without binding an unused error variable.

Comprehensive Tutorial

Want an in-depth understanding of this topic?

Read our complete, interactive tutorial covering memory management, edge cases, and best practices.

Read the full error handling tutorial →