# Error Handling in JavaScript: Try, Catch, Finally

## Error Handling in JavaScript: Building Resilient Code

Imagine a user fills out a form on your website, but a network glitch or a typo causes the code to crash. Without error handling, the entire application freezes, leaving the user with a blank screen and a bad experience.

In JavaScript, **Error Handling** is the art of "graceful failure"—ensuring that even when something goes wrong, your program knows how to recover or, at the very least, explain what happened.

* * *

## What are Errors in JavaScript?

Errors (or "exceptions") occur when your code encounters a situation it doesn't know how to handle. These generally fall into two categories:

1.  **Syntax Errors:** Typos or breaking the rules of the language (detected before the code runs).
    
2.  **Runtime Errors:** Errors that occur while the code is executing, such as trying to call a method on `undefined` or failing to fetch data from an API.
    

* * *

## The Power Trio: Try, Catch, and Finally

JavaScript provides a structured way to handle these runtime hiccups using the `try...catch...finally` statement.

### 1\. The `try` Block

This is where you wrap the code that *might* fail. It’s your "safety net."

### 2\. The `catch` Block

If an error occurs inside the `try` block, JavaScript immediately jumps to the `catch` block. This prevents the script from dying and gives you an `error` object containing details about what went wrong.

### 3\. The `finally` Block

This block runs **no matter what**—whether an error occurred or not. It is typically used for "cleanup" tasks, like closing a database connection or hiding a loading spinner.

JavaScript

```plaintext
try {
    // Code that might throw an error
    let data = JSON.parse(userInput); 
    console.log("Success:", data);
} catch (error) {
    // Code to handle the error
    console.error("Failed to parse JSON:", error.message);
} finally {
    // Code that runs regardless of the outcome
    stopLoadingSpinner();
}
```

* * *

## Throwing Custom Errors

Sometimes, the code isn't technically "broken" by JavaScript's rules, but it's wrong for your business logic. For example, if a user enters a negative age, you can manually **throw** an error to trigger the catch block.

JavaScript

```plaintext
function checkAge(age) {
    if (age < 0) {
        throw new Error("Age cannot be negative!");
    }
    return true;
}

try {
    checkAge(-5);
} catch (err) {
    console.log("Caught custom error: " + err.message);
}
```

* * *

## Why Error Handling Matters

*   **User Experience:** Instead of a broken UI, you can show a helpful message like "Please check your internet connection."
    
*   **Debugging:** By catching errors, you can log them to services like Sentry or LogRocket, helping you find and fix bugs faster.
    
*   **Security:** Unhandled errors can sometimes leak sensitive information about your server structure or database logic.
    
*   **Graceful Failure:** It allows specific parts of your app to fail without crashing the entire system.
    

### The Execution Flow at a Glance

<table style="min-width: 75px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p><strong>Block</strong></p></td><td colspan="1" rowspan="1"><p><strong>When does it run?</strong></p></td><td colspan="1" rowspan="1"><p><strong>Purpose</strong></p></td></tr><tr><td colspan="1" rowspan="1"><p><code>try</code></p></td><td colspan="1" rowspan="1"><p>Always</p></td><td colspan="1" rowspan="1"><p>Executes the main logic.</p></td></tr><tr><td colspan="1" rowspan="1"><p><code>catch</code></p></td><td colspan="1" rowspan="1"><p>Only on error</p></td><td colspan="1" rowspan="1"><p>Handles the exception and prevents a crash.</p></td></tr><tr><td colspan="1" rowspan="1"><p><code>finally</code></p></td><td colspan="1" rowspan="1"><p>Always</p></td><td colspan="1" rowspan="1"><p>Finalizes processes (cleanup).</p></td></tr></tbody></table>

* * *

> **Key Takeaway:** Good developers don't write code that never fails; they write code that fails predictably and recovers elegantly.
