# Error Handling in JavaScript: Try, Catch, Finally

While building applications, errors are unavoidable. A user might enter invalid data, an API might fail, or the code itself might encounter unexpected conditions. If these errors are not handled properly, the application can crash or behave unpredictably.

Error handling in JavaScript allows developers to manage such situations gracefully. Instead of breaking the application, it ensures that errors are caught, meaningful messages are shown, and the system continues to function properly.

In this blog, you will learn:

*   What errors are in JavaScript
    
*   How try, catch, and finally work
    
*   How to throw custom errors
    
*   Why error handling is important in real-world applications
    

## What is Error Handling in JavaScript?

Error handling is the process of detecting, managing, and responding to runtime errors in a controlled way.

### Types of Errors:

*   Syntax Error: Occurs when there is a mistake in the code structure
    
*   Reference Error: Occurs when accessing a variable that is not defined
    
*   Type Error: Occurs when a value is used in an invalid way
    

### Example:

```js
console.log(userName); // ReferenceError: userName is not defined
```

Without proper handling, this error would stop the execution of the program.

## Real-Life Example

Consider a simple banking scenario.

A user tries to withdraw money from their account:

*   The system attempts the transaction
    
*   If the balance is insufficient, an error occurs
    
*   The system informs the user instead of crashing
    
*   The transaction attempt is still recorded
    

This is exactly how error handling works in programming. The system anticipates failure and responds appropriately.

## How Error Handling Works

JavaScript provides try and catch blocks to handle errors.

### Example:

```js
try {
  let data = JSON.parse('invalid json');
  console.log(data);
} catch (error) {
  console.log("An error occurred:", error.message);
}
```

Explanation:

*   The code inside try is executed first
    
*   If an error occurs, execution immediately moves to catch
    
*   The catch block receives the error object
    
*   The application continues running instead of crashing
    

## The finally Block

The finally block is used to execute code regardless of whether an error occurs or not.

### Example:

```js
try {
  console.log("Processing transaction...");
} catch (error) {
  console.log("Error occurred");
} finally {
  console.log("Transaction process completed");
}
```

### Use Cases:

*   Closing database connections
    
*   Stopping loading indicators
    
*   Releasing resources
    

The finally block is especially useful when certain operations must always be performed.

## Error Handling Flow

![](https://cdn.hashnode.com/uploads/covers/69501e8b80eb08d5055e2d2e/0528d13a-c922-4910-93a2-a9d43113f902.png align="center")

This flow ensures that errors are handled without interrupting the overall program.

## Throwing Custom Errors

JavaScript allows developers to create their own errors using the throw keyword.

### Example:

```js
function withdraw(amount, balance) {
  if (amount > balance) {
    throw new Error("Insufficient balance");
  }
  return balance - amount;
}

try {
  let remainingBalance = withdraw(5000, 2000);
  console.log("Remaining Balance:", remainingBalance);
} catch (error) {
  console.log("Transaction failed:", error.message);
}
```

Explanation:

*   A custom error is thrown when the condition fails
    
*   The catch block handles the error and displays a meaningful message
    

## Real-World Use Case

In a real banking application:

```js
function withdraw(amount, balance) {
  if (amount > balance) {
    throw new Error("Insufficient balance");
  }
  return balance - amount;
}

try {
  let balance = withdraw(5000, 2000);
  console.log("Transaction successful:", balance);
} catch (error) {
  console.log("Transaction failed:", error.message);
} finally {
  console.log("Transaction attempt recorded");
}
```

Here:

*   The system prevents invalid transactions
    
*   It informs the user properly
    
*   It logs the attempt regardless of success or failure
    

## Why Error Handling Matters

### Without Error Handling:

*   Applications may crash unexpectedly
    
*   Users receive unclear or technical error messages
    
*   Debugging becomes difficult
    

### With Error Handling:

*   Applications fail gracefully
    
*   Users receive clear feedback
    
*   Debugging becomes easier
    
*   Systems become more stable and reliable
    

## Best Practices

*   Use try-catch only where necessary, not everywhere
    
*   Always provide meaningful error messages
    
*   Handle errors in asynchronous operations as well
    
*   Log errors for debugging and monitoring
    
*   Avoid exposing sensitive information in error messages
    

## Conclusion

Error handling is an essential part of writing reliable JavaScript applications. It ensures that even when something goes wrong, the application continues to behave in a controlled and predictable way.

By using try, catch, finally, and custom errors, developers can build systems that are robust, user-friendly, and easier to maintain.

* * *
