# Error Handling in JavaScript: Try, Catch, Finally



No matter how carefully you write code, errors are a normal part of programming.

Applications can fail because of:

*   Invalid user input
    
*   Missing data
    
*   Network problems
    
*   Bugs in code
    
*   Unexpected conditions
    

Good developers don’t just write code that works — they also write code that handles failures gracefully.

That’s where JavaScript error handling becomes important.

In this beginner-friendly guide, you’ll learn:

*   What errors are in JavaScript
    
*   Using `try` and `catch`
    
*   Understanding the `finally` block
    
*   Throwing custom errors
    
*   Why error handling matters
    

By the end, you’ll understand how to prevent your programs from crashing unexpectedly.

* * *

# What Are Errors in JavaScript?

An error happens when JavaScript encounters a problem it cannot handle normally.

Example:

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

Output:

```text
ReferenceError: userName is not defined
```

The variable does not exist, so JavaScript throws an error.

* * *

# Runtime Errors

Errors that occur while the program is running are called **runtime errors**.

These errors stop code execution if they are not handled properly.

* * *

# Example of Runtime Error

```javascript
const user = null;

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

Output:

```text
TypeError: Cannot read properties of null
```

Since `user` is `null`, JavaScript cannot access `.name`.

* * *

# Why Error Handling Matters

Without error handling:

*   Programs crash unexpectedly
    
*   Users see broken applications
    
*   Debugging becomes difficult
    

With proper error handling:

*   Applications fail gracefully
    
*   Developers get useful debugging information
    
*   Users get better experience
    

* * *

# Understanding Graceful Failure

Graceful failure means:

> Even when something goes wrong, the application continues working properly.

Instead of crashing completely, the program can:

*   Show a meaningful message
    
*   Retry an operation
    
*   Continue running safely
    

* * *

# What is try and catch?

JavaScript provides:

*   `try`
    
*   `catch`
    

to handle errors safely.

* * *

# Basic Syntax

```javascript
try {
  // code that may cause error
} catch (error) {
  // code to handle error
}
```

* * *

# How It Works

1.  JavaScript runs code inside `try`
    
2.  If no error occurs → everything runs normally
    
3.  If an error occurs → execution jumps to `catch`
    
4.  The error gets handled safely
    

* * *

# First Example of try and catch

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

Output:

```text
Something went wrong
```

Instead of crashing, the program handles the error gracefully.

* * *

# Accessing the Error Object

The `catch` block receives an error object.

* * *

# Example

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

Output may look like:

```text
ReferenceError: userName is not defined
```

* * *

# Useful Error Properties

| Property | Meaning |
| --- | --- |
| `error.name` | Type of error |
| `error.message` | Error description |

* * *

# Example

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

Output:

```text
ReferenceError
userName is not defined
```

* * *

# Error Handling Flow Diagram

```text
Start
  │
  ▼
Try Block Executes
  │
  ├── No Error ──► Continue Program
  │
  └── Error Occurs
          │
          ▼
     Catch Block Executes
          │
          ▼
     Program Continues
```

* * *

# The finally Block

JavaScript also provides a `finally` block.

The `finally` block always runs:

*   Whether error happens or not
    
*   Whether `catch` runs or not
    

* * *

# Syntax

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

* * *

# Example

```javascript
try {
  console.log("Inside try block");
} catch (error) {
  console.log("Inside catch block");
} finally {
  console.log("Finally block executed");
}
```

Output:

```text
Inside try block
Finally block executed
```

* * *

# Example with Error

```javascript
try {
  console.log(userName);
} catch (error) {
  console.log("Error handled");
} finally {
  console.log("Finally always runs");
}
```

Output:

```text
Error handled
Finally always runs
```

* * *

# Why finally is Useful

The `finally` block is commonly used for:

*   Closing database connections
    
*   Stopping loaders
    
*   Cleaning resources
    
*   Closing files
    
*   Resetting application state
    

It ensures cleanup code always runs.

* * *

# Try → Catch → Finally Execution Order

```text
Try Block
    │
    ├── Error? ── No ──► Finally
    │
    └── Yes
          │
          ▼
        Catch
          │
          ▼
        Finally
```

* * *

# Throwing Custom Errors

JavaScript allows developers to create their own errors using:

```javascript
throw
```

This is useful when validating data or enforcing rules.

* * *

# Basic Example

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

* * *

# Example with try and catch

```javascript
try {
  throw new Error("Invalid password");
} catch (error) {
  console.log(error.message);
}
```

Output:

```text
Invalid password
```

* * *

# Real-World Validation Example

```javascript
const age = 15;

try {
  if (age < 18) {
    throw new Error("You must be 18 or older");
  }

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

Output:

```text
You must be 18 or older
```

* * *

# Why Custom Errors Are Helpful

Custom errors help developers:

*   Validate user input
    
*   Prevent invalid operations
    
*   Improve debugging
    
*   Create meaningful error messages
    

* * *

# Common Types of JavaScript Errors

| Error Type | Description |
| --- | --- |
| `ReferenceError` | Variable not defined |
| `TypeError` | Invalid operation on value |
| `SyntaxError` | Invalid code syntax |
| `RangeError` | Value out of allowed range |

* * *

# Example of TypeError

```javascript
const number = 10;

number.toUpperCase();
```

Output:

```text
TypeError
```

Numbers do not have `toUpperCase()` method.

* * *

# Common Beginner Mistakes

## 1\. Using try-catch Everywhere

Not every line needs error handling.

Use it only where failures are possible.

* * *

## 2\. Ignoring Errors Completely

This is bad practice:

```javascript
catch (error) {}
```

Always log or handle errors meaningfully.

* * *

## 3\. Throwing Strings Instead of Error Objects

Avoid:

```javascript
throw "Something went wrong";
```

Prefer:

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

* * *

# Real-World Use Cases of Error Handling

Error handling is used in:

*   API requests
    
*   Form validation
    
*   Payment systems
    
*   Authentication
    
*   Database operations
    

Companies like Stripe and PayPal rely heavily on strong error handling systems to prevent failures in critical operations.

* * *

# Debugging Benefits of Error Handling

Good error handling helps developers:

✅ Identify bugs faster ✅ Understand application failures ✅ Prevent crashes ✅ Improve user experience ✅ Maintain stable applications

* * *

# Assignment Practice

Try this yourself.

* * *

# Task

1.  Create a variable `age`
    
2.  If age is less than 18, throw custom error
    
3.  Handle error using `try` and `catch`
    
4.  Add a `finally` block
    

* * *

# Example Solution

```javascript
const age = 16;

try {
  if (age < 18) {
    throw new Error("Access denied");
  }

  console.log("Welcome");
} catch (error) {
  console.log(error.message);
} finally {
  console.log("Execution completed");
}
```

* * *

# Final Thoughts

Errors are unavoidable in programming, but crashing applications are avoidable.

You learned:

✅ What errors are in JavaScript ✅ How `try` and `catch` work ✅ The purpose of `finally` ✅ How to throw custom errors ✅ Why error handling matters

The key goal of error handling is not to hide problems — it is to handle them intelligently and keep applications stable.

As your JavaScript applications grow larger, proper error handling becomes one of the most important programming skills to master.
