Back to Curriculum

Error Handling

📚 Lesson 8 of 20 ⏱️ 30 min

Error Handling

30 min

Errors are inevitable in programming. JavaScript provides the `try...catch...finally` mechanism to handle them gracefully instead of crashing the application.

The `try` block contains code that might throw an exception. If it does, execution jumps immediately to the `catch` block, where you can handle the error (e.g., log it, show a user message).

The `finally` block executes *regardless* of whether an error occurred or not. It's perfect for cleanup tasks like closing database connections or hiding loading spinners.

You can manually throw errors using the `throw` keyword. It's best practice to throw `Error` objects (e.g., `throw new Error('Something went wrong')`) rather than strings, as objects capture the stack trace.

Key Concepts

  • Try/Catch/Finally flow.
  • The `Error` object and Stack Traces.
  • Throwing custom errors.
  • Synchronous vs. Asynchronous error handling.
  • Global error handlers (`window.onerror`).

Learning Objectives

Master

  • Implementing robust error handling logic
  • Creating custom error classes
  • Cleaning up resources with `finally`
  • Differentiating between operational and programmer errors

Develop

  • Resilient application design
  • User-friendly error reporting
  • Debugging skills

Tips

  • Don't put too much code in a single `try` block; keep it focused.
  • Always log errors to a monitoring service (like Sentry) in production.
  • Use `console.error()` for errors to make them stand out in the dev tools.
  • Handle specific error types if possible (e.g., `if (err instanceof TypeError)`).

Common Pitfalls

  • Using `try...catch` for flow control (it's slow and confusing).
  • Swallowing errors (empty catch block) – never do this!
  • Throwing strings (`throw 'error'`) instead of Error objects (no stack trace).
  • Forgetting that `try...catch` doesn't catch errors in asynchronous callbacks (unless using async/await).

Summary

  • Errors should be handled, not ignored.
  • Try/Catch prevents app crashes.
  • Finally ensures cleanup.
  • Error objects provide context.

Exercise

Write a `try...catch` block to handle a potential error.

try {
  // This will cause an error
  myFunction(); 
} catch (error) {
  console.error("An error occurred:", error.message);
}

Exercise Tips

  • Add a finally block to demonstrate cleanup operations.
  • Throw custom errors with new Error('Custom message') for better debugging.
  • Use error.name and error.stack to get more information about the error.
  • Try catching specific error types: catch (e) { if (e instanceof TypeError) ... }

Code Editor

Output