Back to Lessons

JavaScript Error Handling

April 5, 2026

Error Handling

Gracefully handle runtime errors and exceptions.

Error Handling Example

try {
    let result = riskyOperation();
} catch (error) {
    console.error("Error:", error.message);
    console.error(error.stack);
} finally {
    console.log("Cleanup");
}

// Custom error
throw new Error("Something went wrong!");
throw new TypeError("Invalid type!");

Key Points

  • try/catch/finally blocks.
  • Error types: Error, TypeError, ReferenceError.
  • error.message, error.stack for debugging.
  • Global window.onerror handler.