← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 1 of 6

JS Error Handling

Error handling is planning what your program does when something goes wrong, like having a spare tire in the car. It keeps one problem from ruining everything.
Syntax
javascript
try {
  // code that may throw
} catch (error) {
  // handle error
}

What Is Error Handling

Error handling means anticipating that some operations can fail and writing code that responds gracefully instead of letting the whole program crash with an uncaught exception.

A try/catch block is the primary tool for this, letting risky code run while still having a defined fallback path if it fails.

उदाहरण: What Is Error Handling

javascript
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `JSON.parse("not valid json")`
  // Call `JSON.parse("not valid json")`
  JSON.parse("not valid json");
// Catch any error, bound to `error`
// Catch any error, bound to `error`
} catch (error) {
  // Print `"Handled gracefully:", error.message` to the console
  // Print `"Handled gracefully:", error.message` to the console
  console.log("Handled gracefully:", error.message);
}

Throwing Errors

You raise a problem with throw, which immediately stops normal execution and looks for the nearest enclosing catch block able to handle it, unwinding the call stack as needed.

You can throw any value in JavaScript, but throwing an Error object (or a subclass of it) is standard practice since it captures a useful stack trace.

उदाहरण: Throwing Errors

javascript
// Define the function `withdraw` taking `balance`, `amount`
// Define the function `withdraw` taking `balance`, `amount`
function withdraw(balance, amount) {
  // Check whether `amount > balance`
  // Check whether `amount > balance`
  if (amount > balance) {
    // Throw a new `Error` with message "Insufficient funds"
    // Throw a new `Error` with message "Insufficient funds"
    throw new Error("Insufficient funds");
  }
  // Return `balance - amount` from this function
  // Return `balance - amount` from this function
  return balance - amount;
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `withdraw(100, 200)`
  // Call `withdraw(100, 200)`
  withdraw(100, 200);
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `e.message` to the console
  // Print `e.message` to the console
  console.log(e.message);
}

Handling Different Situations

Different failures need different responses — a missing network connection might warrant a retry, while invalid user input should show a message rather than silently failing.

Treating every error identically, with one generic catch-all message, often hides useful information that could help the user or the developer.

उदाहरण: Handling Different Situations

javascript
// Define the function `processInput` taking `value`
// Define the function `processInput` taking `value`
function processInput(value) {
  // Check whether `typeof value !== "number"`
  // Check whether `typeof value !== "number"`
  if (typeof value !== "number") {
    // Print "Invalid input, please enter a number" to the console
    // Print "Invalid input, please enter a number" to the console
    console.log("Invalid input, please enter a number");
  // Otherwise, run this branch
  // Otherwise, run this branch
  } else {
    // Print `"Processing:", value` to the console
    // Print `"Processing:", value` to the console
    console.log("Processing:", value);
  }
}
// Call `processInput("abc")`
// Call `processInput("abc")`
processInput("abc");

Good Error Handling

Good error handling reports enough detail to diagnose the problem, via error.message or a custom error type, without leaking sensitive internals like stack traces or database details to the end user.

उदाहरण: Good Error Handling

javascript
try {
  throw new Error("Database connection failed");
} catch (error) {
  console.log("Error occurred:", error.message); // useful detail, no internals leaked
}

Error Handling Best Practices

As a rule of thumb, catch errors close to where you can actually do something useful about them, and let errors you can't handle propagate up to a boundary that can.

Logging errors with enough context (what operation failed, with what input) makes debugging production issues dramatically easier later.

उदाहरण: Error Handling Best Practices

javascript
// Define the function `riskyOperation` with no parameters
// Define the function `riskyOperation` with no parameters
function riskyOperation() {
  // Throw a new `Error` with message "Something failed"
  // Throw a new `Error` with message "Something failed"
  throw new Error("Something failed");
}
// Try running this block; jump to `catch` if it throws
// Try running this block; jump to `catch` if it throws
try {
  // Call `riskyOperation()`
  // Call `riskyOperation()`
  riskyOperation();
// Catch any error, bound to `e`
// Catch any error, bound to `e`
} catch (e) {
  // Print `"Handled where we can act:", e.message` to the console
  // Print `"Handled where we can act:", e.message` to the console
  console.log("Handled where we can act:", e.message);
}
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.