JAVASCRIPT

JavaScript Error Handling: Syntax, Usage, and Examples

JavaScript error handling is the process of managing and responding to runtime errors in your code. Effective error handling in JavaScript prevents crashes, improves user experience, and makes debugging easier. JavaScript provides built-in mechanisms to catch, throw, and handle errors gracefully.


How to Use JavaScript Error Handling

JavaScript provides the try...catch statement to catch and handle errors without stopping script execution.

Basic Syntax

try {
  // Code that may throw an error
} catch (error) {
  // Code to handle the error
} finally {
  // Code that always runs, regardless of an error
}
  • try – Runs the code block and watches for errors.
  • catch – Executes if an error occurs in try, capturing the error object.
  • finally – Runs code whether or not an error occurred (optional).

Throwing Custom Errors

You can manually throw an error using the throw statement.

function checkAge(age) {
  if (age < 18) {
    throw new Error("You must be 18 or older.");
  }
  return "Access granted";
}

try {
  console.log(checkAge(16));
} catch (error) {
  console.log("Error:", error.message);
}

When to Use JavaScript Error Handling

Error handling in JavaScript is essential in situations where unexpected issues might occur. Here are three common use cases:

  1. Handling API and network errors – If an API request fails, error handling can retry the request or display an error message.
  2. Validating user input – If a user enters invalid data, error handling can prompt them to fix it instead of breaking the application.
  3. Preventing application crashes – When dealing with unexpected values or missing data, structured error handling ensures the app continues running.

Examples of JavaScript Error Handling

Catching Errors in Asynchronous Code

When working with asynchronous functions and promises, errors can be handled using .catch().

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error("Error fetching data:", error.message));

If the fetch request fails (e.g., no internet connection), the .catch() method handles the error gracefully.

Handling Errors with async and await

For cleaner error handling in asynchronous functions, use try...catch.

async function fetchData() {
  try {
    const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error("Error fetching data:", error.message);
  }
}

fetchData();

This prevents unhandled promise rejections and allows a structured response to errors.

Using finally to Clean Up

The finally block ensures cleanup actions always run, even if an error occurs.

function processTask() {
  try {
    console.log("Processing...");
    throw new Error("Something went wrong!");
  } catch (error) {
    console.error("Caught error:", error.message);
  } finally {
    console.log("Task completed (cleaning up resources).");
  }
}

processTask();

Learn More About JavaScript Error Handling

Different Types of JavaScript Errors

JavaScript errors fall into different categories:

  1. ReferenceError – Trying to use a variable that hasn’t been defined.

    console.log(nonExistentVar); // ReferenceError
    
  2. TypeError – Calling a method on an undefined or incorrect data type.

    let num = 42;
    num.toUpperCase(); // TypeError: num.toUpperCase is not a function
    
  3. SyntaxError – Writing invalid JavaScript syntax.

    javascript
    CopyEdit
    console.log("Hello; // SyntaxError: missing closing quote
    
    
  4. RangeError – Exceeding the allowed range of values.

    function recurse() {
      return recurse();
    }
    recurse(); // RangeError: Maximum call stack size exceeded
    

Using Error Object Properties

The Error object provides useful properties when handling errors.

try {
  throw new Error("Custom error message");
} catch (error) {
  console.log(error.name);  // "Error"
  console.log(error.message);  // "Custom error message"
  console.log(error.stack);  // Stack trace for debugging
}

Creating Custom Error Classes

For better error categorization, create custom error classes by extending the Error object.

class ValidationError extends Error {
  constructor(message) {
    super(message);
    this.name = "ValidationError";
  }
}

try {
  throw new ValidationError("Invalid input!");
} catch (error) {
  console.log(error.name); // "ValidationError"
  console.log(error.message); // "Invalid input!"
}

Global Error Handling with window.onerror

In browsers, you can catch uncaught errors globally.

window.onerror = function (message, source, lineno, colno, error) {
  console.error(`Error: ${message} at ${source}:${lineno}:${colno}`);
};

Debugging Errors in JavaScript

When debugging errors:

  • Use console.log() to track variable values.
  • Use console.error() for errors to stand out in the console.
  • Check browser developer tools (F12 or Cmd + Opt + I).

JavaScript error handling ensures smooth program execution by catching and responding to unexpected errors. Use try...catch, throw, and finally to manage errors effectively.

Learn to Code in JavaScript for Free
Start learning now
button icon
To advance beyond this tutorial and learn JavaScript by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH