Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Updated
6 min read
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:

console.log(userName);

Output:

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:

Runtime Errors

Example:

let user = null;

console.log(user.name);

Output:

TypeError

because we cannot access properties of null.


Why Error Handling Matters

Without proper handling:

Error occurs
     ↓
Program crashes

With error handling:

Error occurs
     ↓
Program handles error safely
     ↓
Application continues running

This is called:

Graceful Failure

What Is try?

The try block contains code that may produce an error.

Example:

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:

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

Output:

Something went wrong

Instead of crashing, the application handles the error gracefully.


Understanding the Flow

try block runs
      ↓
Error occurs?
   ↙       ↘
 No         Yes
 ↓           ↓
Continue    catch block runs

Accessing Error Information

The catch block receives an error object.

Example:

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

Output:

ReferenceError: userName is not defined

This helps developers debug issues.


Error Handling Flow

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:

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

Output:

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

try
 ↓
catch (if error happens)
 ↓
finally (always runs)

Example with Actual Error

try {
  let user = null;

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

Output:

Cannot read property
Execution completed

Throwing Custom Errors

JavaScript also allows developers to create their own errors using:

throw

Simple Custom Error Example

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:

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:

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

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

Missing bracket causes:

SyntaxError

Graceful Failure Example

Without handling:

Application crashes

With handling:

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:

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:

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:

throw

4. Print Error Message

Use:

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:

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!