#atom
Title: try, catch, and finally in JavaScript

Content:
The try, catch, and finally statements in JavaScript are used for error handling. They allow you to "try" a block of code, "catch" any errors that occur, and optionally execute a "finally" block regardless of whether an error was thrown. This mechanism helps manage runtime errors gracefully without crashing the program.

Syntax:

try {
  // Code that may throw an error
} catch (error) {
  // Code to handle the error
} finally {
  // Code that runs regardless of whether an error occurred
}

Key Concepts:

  1. try Block:

    • The try block contains the code that might throw an exception.
    • If an error occurs, the rest of the try block is skipped, and control is passed to the catch block.
  2. catch Block:

    • The catch block is executed if an error is thrown in the try block.
    • It receives the error object, which contains information about the error (e.g., error.message, error.name).
    • You can use this block to log the error, display a user-friendly message, or recover from the error.
  3. finally Block:

    • The finally block is optional and runs after the try and catch blocks, regardless of whether an error occurred.
    • It is typically used for cleanup tasks, such as closing files, releasing resources, or resetting state.

Example:

function divide(a, b) {
  try {
    if (b === 0) {
      throw new Error("Division by zero is not allowed.");
    }
    return a / b;
  } catch (error) {
    console.error(`Error: ${error.message}`);
    return null;
  } finally {
    console.log("Division operation attempted.");
  }
}

console.log(divide(10, 2)); // 5, logs "Division operation attempted."
console.log(divide(10, 0)); // null, logs "Error: Division by zero is not allowed." and "Division operation attempted."

Error Object:

Custom Errors:

Linked Cards:

Tags: #JavaScript #ErrorHandling #TryCatch #Finally #ControlStructures #CustomErrors

Connections:


Sources: