JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsjavascript
PrevNext

Learn the concept

Error Handling

javascript
junior
error-handling

How does try/catch work in JavaScript and when should you use it?

error-handling
try-catch
errors
async
fundamentals
Quick Answer

try/catch wraps code that might throw errors: the try block runs the code, catch handles any error that occurs, and the optional finally block always executes regardless of the outcome. Use it for operations that can fail at runtime like API calls, JSON parsing, and user input processing.

Detailed Explanation

Error handling prevents your application from crashing when unexpected things happen.

Syntax:

JavaScript
try {
  // code that might throw
} catch (error) {
  // handle the error
} finally {
  // always runs (optional)
}

The error object has properties:

  • error.message — human-readable description
  • error.name — error type (TypeError, ReferenceError, etc.)
  • error.stack — call stack trace

Common error types:

  • TypeError — wrong type (e.g., calling non-function)
  • ReferenceError — undefined variable
  • SyntaxError — invalid code
  • RangeError — value out of range

When to use:

  • JSON.parse() with unknown input
  • API/network requests
  • Accessing properties that might not exist
  • File operations (Node.js)

Code Examples

Basic try/catch/finallyJavaScript
// Basic usage
try {
  const data = JSON.parse('{invalid json}');
} catch (error) {
  console.error('Parse failed:', error.message);
  // SyntaxError with message about invalid JSON
} finally {
  console.log('This always runs');
}

// Throwing custom errors
function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

try {
  const result = divide(10, 0);
} catch (error) {
  console.error(error.message); // 'Cannot divide by zero'
}

Real-World Applications

Use Cases

API Error Handling

Catching fetch failures, HTTP errors, and JSON parsing errors with appropriate user feedback

Form Validation

Throwing and catching custom validation errors for invalid user input before submission

Graceful Degradation

Providing fallback behavior when optional features or third-party services fail at runtime

Mini Projects

API Client with Retry

beginner

Build a fetch wrapper with automatic retry logic and exponential backoff for failed requests

Error Logger

intermediate

Build an error tracking utility that captures, categorizes, and reports application errors with stack traces

Industry Examples

Sentry

Real-time error tracking and performance monitoring that automatically captures uncaught JavaScript exceptions

Express

Error-handling middleware with (err, req, res, next) signature provides centralized error handling for Node.js web applications

React

Error Boundaries use getDerivedStateFromError and componentDidCatch to catch rendering errors in child components and display fallback UI

Resources

MDN - try...catch

docs

JavaScript.info - Error handling

article
Previous
How do you select and manipulate DOM elements in JavaScript?
Next
What are template literals and tagged templates in JavaScript?
PrevNext