# Error Handling in Javascript: Try, Catch, Finally

So, what do you mean by **Errors in JavaScript**?

Well technically!!!...

Errors are issues that occur when your JavaScript code stops executing as expected.

But wait…

This sounds like your maths teacher explaining integration 😵‍💫

So let’s understand this in **our way**.

* * *

## When Life Breaks… JavaScript Also Breaks

Imagine this:

You are ordering food online 🍔

You click **“Place Order”**…

And suddenly… nothing happens.

No confirmation, no error, no refund

Just silence…

That… my friend… is what we call **bad error handling**.

Now let’s bring this to code.

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

But…

```js
const user = null;
```

Boom 💥

👉 Error: Cannot read properties of null

* * *

## Types of Errors (Real Life Style)

JavaScript errors are mainly of 3 types:

### 1\. Syntax Error

Your code is written incorrectly.

Like writing:

```js
if (true {
  console.log("Hello");
}
```

Missing `)`… and JavaScript says:

👉 “Bhai pehle grammar seekh ke aa”

* * *

### 2\. Runtime Error

Code runs… but crashes during execution.

```js
const user = null;
console.log(user.name);
```

This is like:

You reached the restaurant… but it's closed 🚪

* * *

### 3\. Logical Error

Code runs perfectly… but gives wrong result.

```js
const total = 10 + "5"; // "105"
```

This is like:

You ordered pizza… got pineapple pizza 🍍🍕

Technically correct… emotionally wrong.

* * *

## Now Comes the Hero — try & catch

So how do we handle errors?

JavaScript gives us a bodyguard 🛡️

👉 `try...catch`

```js
try {
  const user = null;
  console.log(user.name);
} catch (error) {
  console.log("Something went wrong");
}
```

* * *

### How it works?

*   `try` → Run risky code
    
*   `catch` → Handle error if it occurs
    

* * *

### Real Life Example

You are transferring money 💸

```js
try {
  transferMoney();
} catch (error) {
  console.log("Transaction failed. Please try again.");
}
```

Instead of app crashing…

👉 User sees a message 👉 Business saves reputation 👉 You save your job 😅

* * *

## The Flow (Important)

Try to visualize this:

```plaintext
Start
  ↓
try block runs
  ↓
Error?
  ↓         ↓
No          Yes
↓           ↓
skip catch  catch runs
  ↓
finally runs (always)
  ↓
End
```

Yes… there is one more player 👇

* * *

## The Finally Block (The Honest Worker)

No matter what happens…

`finally` will always run.

```js
try {
  console.log("Trying...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("I will always run 😎");
}
```

* * *

### Real Life Example

ATM Machine:

```js
try {
  withdrawMoney();
} catch (error) {
  console.log("Transaction failed");
} finally {
  ejectCard(); // always happens
}
```

Even if money fails…

👉 Card always comes out

* * *

## Throwing Custom Errors (Ab Developer Bolega 😎)

Sometimes default errors are not enough.

We want to control the message.

```js
function withdraw(amount) {
  if (amount > 10000) {
    throw new Error("Limit exceeded bhai 😅");
  }
  return "Money withdrawn";
}

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

* * *

### Why This is Powerful?

Instead of random crash…

👉 You define the problem 👉 You define the message 👉 You guide the user

* * *

## Graceful Failure (The Real Goal)

Good developers don’t write bug-free code…

👉 They write code that **fails gracefully**

Bad Example ❌ App crashes

Good Example ✅ App says:

> “Something went wrong, please try again”

* * *

## Debugging Benefits (Why You Should Care)

Error handling helps you:

*   Find bugs faster 🔍
    
*   Prevent app crashes 🚫
    
*   Improve user experience ❤️
    
*   Write production-ready code 🚀
    

* * *

## One Small Example (Real World Combo)

```js
function login(user) {
  try {
    if (!user) {
      throw new Error("User not found");
    }

    console.log("Welcome " + user.name);

  } catch (error) {
    console.log(error.message);
  } finally {
    console.log("Login attempt finished");
  }
}

login(null);
```

Output:

```plaintext
User not found
Login attempt finished
```

* * *

## Final Thoughts

Errors are not enemies…

They are signals 🚨

They tell you:

👉 “Something is wrong… fix me”

If you ignore them…

Your app becomes chaos 😵

If you handle them…

You become a real developer 💪

* * *

## Homework (Don’t Run Away 😏)

### Q1

What will be the output?

```js
try {
  console.log(a);
} catch (e) {
  console.log("Error handled");
}
```

* * *

### Q2

Fix this code using try-catch:

```js
const data = JSON.parse("{name: 'Barun'}");
console.log(data);
```

* * *

### Q3

Create a function:

*   If age < 18 → throw error
    
*   Else → print "Access granted."
    

* * *

## Last Line (Important)

A good developer writes code…

A great developer handles failure.

And trust me…

In real world…

Failure comes more often than success 😄

* * *

Inspired by the style and storytelling approach from the shared blog examples
