# Error Handling in JavaScript: Try, Catch, Finally

While writing JavaScript programs, errors are completely normal.

Even experienced developers encounter errors every day.

The important part is not avoiding errors completely, but handling them properly.

Without error handling:

*   applications can crash
    
*   users may see broken pages
    
*   debugging becomes difficult
    

JavaScript provides tools like:

*   `try`
    
*   `catch`
    
*   `finally`
    
*   `throw`
    

to manage errors gracefully.

In this article, we’ll learn:

*   What errors are in JavaScript
    
*   Using try and catch blocks
    
*   The finally block
    
*   Throwing custom errors
    
*   Why error handling matters
    

Let’s begin.

* * *

## What Are Errors in JavaScript?

Errors are problems that occur while code is running.

Example:

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

Output:

```id="err002"
ReferenceError: userName is not defined
```

JavaScript stops execution when it encounters an unhandled error.

* * *

## Why Errors Happen

Errors can occur because of:

*   wrong variable names
    
*   invalid operations
    
*   API failures
    
*   network issues
    
*   incorrect user input
    

Errors are a natural part of programming.

* * *

## Runtime Errors

Some errors happen while the program is running.

These are called:

```id="err003"
Runtime Errors
```

Example:

```javascript
let user = null;

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

Output:

```id="err005"
TypeError
```

because we cannot access properties of `null`.

* * *

## Why Error Handling Matters

Without proper handling:

```id="err006"
Error occurs
     ↓
Program crashes
```

With error handling:

```id="err007"
Error occurs
     ↓
Program handles error safely
     ↓
Application continues running
```

This is called:

```id="err008"
Graceful Failure
```

* * *

## What Is `try`?

The `try` block contains code that may produce an error.

Example:

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

JavaScript attempts to execute this code.

If an error occurs, control moves to `catch`.

* * *

## What Is `catch`?

The `catch` block handles errors safely.

Example:

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

Output:

```id="err011"
Something went wrong
```

Instead of crashing, the application handles the error gracefully.

* * *

## Understanding the Flow

```id="err012"
try block runs
      ↓
Error occurs?
   ↙       ↘
 No         Yes
 ↓           ↓
Continue    catch block runs
```

* * *

## Accessing Error Information

The `catch` block receives an error object.

Example:

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

Output:

```id="err014"
ReferenceError: userName is not defined
```

This helps developers debug issues.

* * *

## Error Handling Flow

```id="err015"
try
 ↓
Code Executes
 ↓
Error?
 ↙      ↘
No       Yes
↓         ↓
Continue  catch
```

* * *

## The `finally` Block

The `finally` block always executes.

Whether:

*   an error occurs
    
*   or no error occurs
    

Example:

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

Output:

```id="err017"
Inside try
Inside finally
```

* * *

## When `finally` Is Useful

`finally` is commonly used for:

*   closing database connections
    
*   stopping loaders
    
*   cleaning resources
    
*   logging completion
    

Because it always runs.

* * *

## Try → Catch → Finally Order

```id="err018"
try
 ↓
catch (if error happens)
 ↓
finally (always runs)
```

* * *

## Example with Actual Error

```javascript
try {
  let user = null;

  console.log(user.name);
} catch (error) {
  console.log("Cannot read property");
} finally {
  console.log("Execution completed");
}
```

Output:

```id="err020"
Cannot read property
Execution completed
```

* * *

## Throwing Custom Errors

JavaScript also allows developers to create their own errors using:

```javascript
throw
```

* * *

## Simple Custom Error Example

```javascript
let age = 15;

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

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

Output:

```id="err023"
Age must be 18 or above
```

* * *

## Why Custom Errors Are Useful

Custom errors help:

✅ Validate user input  
✅ Prevent invalid operations  
✅ Provide meaningful messages  
✅ Improve debugging

* * *

## Real-World Example

Imagine a login system.

Flow:

```id="err024"
User enters password
        ↓
Password invalid?
     ↙        ↘
   Yes         No
    ↓           ↓
Show Error    Login Success
```

Applications constantly use error handling like this.

* * *

## Common Types of JavaScript Errors

| Error Type | Meaning |
| --- | --- |
| ReferenceError | Variable does not exist |
| TypeError | Invalid operation on value |
| SyntaxError | Incorrect syntax |
| RangeError | Value out of allowed range |

* * *

## Example of Syntax Error

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

Missing bracket causes:

```id="err026"
SyntaxError
```

* * *

## Graceful Failure Example

Without handling:

```id="err027"
Application crashes
```

With handling:

```id="err028"
User sees friendly message
```

This creates better user experience.

* * *

## Common Beginner Mistakes

### Ignoring Errors

Never leave errors unhandled in real applications.

* * *

### Empty Catch Blocks

Avoid this:

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

Always log or handle the error properly.

* * *

### Using `try-catch` Everywhere

Use it where errors are actually expected.

Too much error handling can reduce readability.

* * *

## Practice Assignment

Try these exercises yourself.

* * *

## 1\. Handle Undefined Variable Error

Use:

```javascript
try-catch
```

to handle a variable error.

* * *

## 2\. Use `finally`

Print a message inside `finally`.

Observe that it always runs.

* * *

## 3\. Throw Custom Error

Create an age validation example using:

```javascript
throw
```

* * *

## 4\. Print Error Message

Use:

```javascript
error.message
```

inside `catch`.

* * *

## Final Thoughts

Errors are an unavoidable part of programming.

Strong developers are not people who never face errors.

They are people who:

*   understand errors
    
*   debug effectively
    
*   handle failures gracefully
    

JavaScript’s:

*   `try`
    
*   `catch`
    
*   `finally`
    
*   `throw`
    

provide powerful tools for managing runtime issues safely.

The key idea is:

```id="err033"
Good applications don't crash easily.
They handle errors gracefully.
```

Understanding error handling is essential for building:

*   reliable applications
    
*   production-ready systems
    
*   professional backend and frontend projects
    

As you continue learning JavaScript, proper error handling will become one of your most important skills.

* * *

And now, you know what Error Handling in JavaScript is.

If you have any doubt or want to connect, feel free to drop a comment — I’d be happy to help.

Thanks for reading, and see you in the next blog!

Peace ✌️ and Happy Learning!
