# Error Handling in JavaScript: Try, Catch, Finally

* * *

When you're writing JavaScript, things will go wrong. It’s not a matter of “if”, it’s “when”.

Maybe a variable is undefined.  
Maybe an API fails.  
Maybe user input is not what you expected.

If you don’t handle these situations properly, your app crashes. And that’s a bad experience.

Let’s understand how JavaScript helps us deal with errors in a clean way.

* * *

Example:

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

If `user` is not defined, JavaScript throws an error.

`ReferenceError: user is not defined`

This is called a runtime error — it happens while the code is running.

Other common errors:

*   `TypeError` --> accessing property on `undefined` or `null`
    
*   `SyntaxError` --> wrong code structure
    
*   `RangeError` --> value out of allowed range
    

* * *

### Using try and catch

JavaScript gives us a way to “try” risky code and handle failure gracefully.

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

Example:

```javascript
try {
  let data = JSON.parse("invalid json");
  console.log(data);
} catch (error) {
  console.log("Something went wrong:", error.message);
}
```

Instead of crashing, this prints:

`Something went wrong: Unexpected token i in JSON`

The app continues running. That’s the key.

* * *

### The finally Block

Sometimes you want something to run no matter what happens.

That's where finally comes in.

Syntax:

```javascript
try {
  // code
} catch (error) {
  // handle error
} finally {
  // always runs
}
```

Example

```javascript
try {
  console.log("Fetching data...");
  throw new Error("Network failed");
} catch (error) {
  console.log("Error:", error.message);
} finally {
  console.log("Cleanup or closing resources");
}
```

Output

`Fetching data...   Error: Network failed   Cleanup or closing resources`

`finally` runs whether error happens or not.

* * *

### Throwing Custom Errors

You're not limited to built-in errors. you can create your own using `throw` keyword.

Example

```javascript
function withdraw(amount) {
  if (amount <= 0) {
    throw new Error("Amount must be greater than zero");
  }
  console.log("Withdrawal successful");
}

try {
  withdraw(-100);
} catch (error) {
  console.log(error.message);
}

// output - Amount must be greater than zero
```

This is useful for:

*   Validating inputs
    
*   Enforcing business rules
    
*   Making errors more meaningful
    

* * *

### Don’t Overuse try-catch

A common mistake is wrapping everything inside `try-catch`.

```javascript
try {
  let x = 10 + 20;
} catch {}
```

No need. This code will never fail.

Use `try-catch` only for:

*   Risky operations (API, parsing, async)
    
*   External data
    
*   Critical sections
    

* * *
