# Error Handling: try/catch

> Don't let your application crash. Learn how to throw, catch, and safely recover from unexpected errors using try, catch, and finally.

Subject: JavaScript | Lesson 51 of 63 | 6 min read
Interactive lesson: https://codewithanimation.in/javascript/error-handling
Previous: [Proxy & Reflect](https://codewithanimation.in/javascript/proxy-and-reflect.md) | Next: [Memory & Garbage Collection](https://codewithanimation.in/javascript/memory-and-garbage-collection.md)

## The Safety Net

In JavaScript, when a fatal error occurs (like trying to read a property on `undefined`), the engine instantly stops executing your script and throws an Exception. If uncaught, this crashes your entire application.

The `try...catch` statement acts as a safety net. You wrap risky code inside the `try` block. If an error occurs, the script doesn't crash; instead, execution immediately jumps into the `catch` block where you can handle it gracefully.

## The Finally Block

Often, you need to run cleanup code regardless of whether the operation succeeded or failed (e.g., hiding a loading spinner, or closing a database connection).

The `finally` block is guaranteed to run after the `try` and `catch` blocks finish, no matter what happened.

## Throwing Custom Errors

You don't have to wait for JavaScript to throw native errors. You can manually trigger an error state using the `throw` keyword.

```javascript
try {
  if (!user.isLoggedIn) {
    throw new Error('Authentication failed');
  }
  showDashboard();
} catch (error) {
  console.log(error.message);
} finally {
  hideLoader();
}
```

## Common mistake: Silent Failures

A common beginner mistake is writing an empty catch block: `catch (e) {}`. This completely swallows the error.

While it prevents the app from crashing, it makes debugging impossible because you have no idea the error occurred. Always at least log the error (`console.error(e)`) or send it to a tracking service.

## Tip: Custom Error Types

You aren't limited to the base `Error` class. JavaScript provides specific error types like `TypeError`, `SyntaxError`, and `ReferenceError`. You can even extend the base `Error` class to create your own custom `ValidationError` or `DatabaseError` classes!

## Try it: The Execution Flow

Use the control panel to simulate different network scenarios. Watch closely how the execution path jumps between the `try`, `catch`, and `finally` blocks depending on what happens.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/error-handling

## Check yourself

### Question 1

What happens to the remaining code inside a `try` block immediately after an error is thrown?

- A. It is skipped entirely, and execution jumps straight to the catch block.
- B. It finishes executing, and then the catch block runs.
- C. It crashes the application.

Correct answer: A

A thrown error acts like an emergency exit. Execution immediately aborts the current block and looks for the nearest catch block in the call stack.

- Why not B: Incorrect. The moment an error is thrown, the try block aborts.
- Why not C: Incorrect. The catch block prevents the crash.

### Question 2

If a `try` block executes successfully without any errors, what happens to the `catch` and `finally` blocks?

- A. The catch block is skipped, but the finally block still runs.
- B. Both are skipped.
- C. Both will run.

Correct answer: A

The `finally` block is the ultimate guarantee in JavaScript. It will always run, making it perfect for cleanup tasks like resetting UI state.

- Why not B: Incorrect. The finally block is guaranteed to run.
- Why not C: Incorrect. The catch block only runs if an error was thrown.

### Question 3

Why should you throw `new Error('msg')` instead of just throwing a string like `throw 'msg'`?

- A. Because the Error object automatically captures the stack trace, showing exactly which line of code caused the error.
- B. Because throwing a string causes a syntax error.
- C. Because catch blocks only accept objects.

Correct answer: A

While `throw 'msg'` is technically valid JavaScript, it is terrible practice because you lose the stack trace, making it incredibly difficult to find where the error originated.

- Why not B: Incorrect. JavaScript allows you to throw any data type, including strings.
- Why not C: Incorrect. Catch blocks will accept whatever was thrown.

## Remember this

- Wrap risky or unpredictable code (like network requests) inside a `try` block.
- If an error occurs, the `try` block immediately aborts and the `catch(error)` block runs.
- The `finally` block runs 100% of the time, regardless of success or failure.
- Use the `throw` keyword to manually trigger an error state.
- Always throw an `Error` object (`throw new Error()`) rather than a raw string so you retain the stack trace.
