# Error Handling in JavaScript: Try, Catch, Finally

Sometimes… your code just breaks.

And not in a “small bug” way.  
I mean the kind where everything stops working.

You click a button → nothing happens.  
You run a function → boom, error.

Let me show you something simple:

```javascript
console.log(user.name);
```

Looks fine, right?

But what if `user` doesn’t exist?  
Your program crashes.

And JavaScript doesn’t politely say “hey, something’s wrong” It just throws an error and stops execution.

That’s where **error handling** comes in.

* * *

## What Are Errors in JavaScript?

In simple words: An error is when JavaScript can’t do what you asked it to do.

Example:

```javascript
console.log(x);
```

If `x` is not defined, you get:

```javascript
ReferenceError: x is not defined
```

There are many types of errors, but don’t overthink it right now.

Just understand this: Errors break your program.

And if you don’t handle them… your app feels broken to users.

* * *

## The Problem: Code Stops Running

Here’s something important.

```javascript
console.log("Start");

console.log(user.name); // error

console.log("End");
```

Output:

```javascript
Start
Error
```

“End” never runs. That’s dangerous. Because one small issue can stop your entire program.

* * *

## Enter try and catch

Now imagine this: Instead of letting your app crash…  
you catch the error and handle it.

That’s exactly what `try...catch` does.

```javascript
try {
  console.log(user.name);
} catch (error) {
  console.log("Something went wrong");
}
```

Now what happens?  
The error is caught  
Your app doesn’t crash  
You stay in control

* * *

### How it actually works

Think of it like this:

*   **try** → “Try running this code”
    
*   **catch** → “If something breaks, handle it here”  
    

```javascript
try {
  // risky code
} catch (error) {
  // fallback logic
}
```

That `error` contains details about what went wrong.

```javascript
catch (error) {
  console.log(error.message);
}
```

Now you’re not blind anymore. You can debug properly.

* * *

## Real-Life Thinking (Important)

Imagine you’re logging in a user.

```javascript
try {
  let data = JSON.parse(userInput);
} catch (error) {
  console.log("Invalid data format");
}
```

Instead of crashing…

you show a message  
user understands  
app continues working  
That’s called **graceful failure,** Not perfect… but controlled.

* * *

## The finally Block (No Escape Zone)

Now comes something interesting.

There are situations where you want some code to run **no matter what happens**

Error or no error. That’s where `finally` comes in.

```javascript
try {
  console.log("Trying...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("This always runs");
}
```

Output:

```javascript
Trying...
This always runs
```

Or even if there’s an error:

```javascript
Error occurred
This always runs
```

`finally` always executes.

* * *

### Why does finally exist?

Because sometimes you need cleanup.

Example:

*   closing a file
    
*   stopping a loader
    
*   ending a process
    

No matter success or failure.

* * *

## Throwing Your Own Errors

Now here’s where things get powerful.

You don’t always wait for JavaScript to throw errors. You can create your own.

```javascript
throw new Error("Something is wrong");
```

Example:

```javascript
let age = -5;

if (age < 0) {
  throw new Error("Age cannot be negative");
}
```

Now combine with try/catch:

```javascript
try {
  let age = -5;

  if (age < 0) {
    throw new Error("Invalid age");
  }

} catch (error) {
  console.log(error.message);
}
```

You define rules  
You control behavior

This is where your code starts becoming smarter.

* * *

## Why Error Handling Actually Matters

Let’s be real.

Without error handling:

*   your app crashes
    
*   users get confused
    
*   debugging becomes painful
    

With error handling:

*   your app stays stable
    
*   users get feedback
    
*   you understand problems faster
    

It’s not about avoiding errors. It’s about handling them properly.

* * *

## Flow of Error Handling (Mental Model)

Think like this:

```javascript
Try → Run code
   ↓
Error? → Yes → Catch block runs
   ↓
Finally → Always runs
```

Or in simple words:

Try it  
If it fails, handle it  
Then finish cleanly

* * *

## Small but Important Insight

Error handling doesn’t make your code perfect.

It makes your code **resilient**. There will always be errors.

But instead of breaking everything… you control the damage.

* * *

## Final Understanding

At first, errors feel like something to avoid.

But the truth is… errors are part of programming.

What actually matters is:

*   how you respond
    
*   how you handle them
    
*   how your program behaves after failure
    

Because real-world applications don’t run in perfect conditions.

They deal with:

*   bad input
    
*   network issues
    
*   unexpected behavior
    

And this… is where **try, catch, and finally** become powerful.

* * *

## Assignment Practice

Try this yourself:

1\. Write code that throws an error  
2\. Handle it using try/catch  
3\. Add a finally block  
4\. Create a custom error using `throw`

Run it. Break it. Fix it. That’s how this really clicks.
