Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

Updated
•5 min read•View as Markdown

What Errors Are in JavaScript

Errors are situations where JavaScript cannot execute code properly. Example:

console.log(userName);

Output:

ReferenceError: userName is not defined

Because the variable does not exist. Errors are a normal part of programming. Every developer faces:

  • syntax errors

  • logic errors

  • runtime errors

  • API errors

  • network errors

The important thing is not avoiding all errors. The important thing is:

Handling errors properly.

Why Errors Happen

Errors can happen for many reasons. Examples:

  • wrong variable names

  • invalid user input

  • failed API requests

  • database failures

  • undefined values

  • incorrect logic

Real applications constantly deal with unexpected situations. So JavaScript provides mechanisms to handle them safely.

Understanding Runtime Errors

Some errors happen during execution.

Example:

const user = undefined;

console.log(user.name);

Output:

TypeError

Because:

  • JavaScript tries accessing name

  • but user is undefined

Without proper handling, the application may crash.

Using try and catch Blocks

JavaScript provides:

try...catch

for handling errors safely.

Basic syntax:

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

How try Works

Inside try block:

  • JavaScript attempts executing code

If no error happens:

  • code runs normally

If an error occurs:

  • execution jumps to catch

Example of try...catch

Example:

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

Output:

Something went wrong

Instead of crashing the application.

Understanding the error Object

Inside catch:

catch (error)

JavaScript provides an error object.

Example:

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

Output:

ReferenceError: userName is not defined

This object contains useful debugging information.

Common Error Properties

Example:

console.log(error.name);
console.log(error.message);

Possible output:

ReferenceError
userName is not defined

This helps developers identify problems faster.

The finally Block

JavaScript also provides:

finally

Syntax:

try {

} catch (error) {

} finally {

}

The finally block always runs.

Whether:

  • error happens

  • or no error happens

Example of finally

Example:

try {
  console.log("Running code");
} catch (error) {
  console.log(error);
} finally {
  console.log("This always runs");
}

Output:

Running code
This always runs

Why finally is Useful

finally is commonly used for:

  • closing database connections

  • stopping loaders

  • cleaning resources

  • removing temporary files

Basically:

cleanup tasks.

Throwing Custom Errors

JavaScript also allows developers to create their own errors. Using:

throw

Simple Custom Error Example

Example:

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

  console.log("Access granted");
}

checkAge(15);

Output:

Error: Age must be 18 or above

Understanding throw

throw manually creates an error. This allows developers to:

  • validate data

  • stop invalid operations

  • enforce rules

Real Use Case of Custom Errors

Example:

  • invalid login

  • weak password

  • payment failure

  • unauthorized access

Instead of silently failing, developers can throw meaningful errors.

Example with try...catch

Example:

function divide(a, b) {
  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }

  return a / b;
}

try {
  console.log(divide(10, 0));
} catch (error) {
  console.log(error.message);
}

Output:

Cannot divide by zero

Why Error Handling Matters

Without proper error handling:

  • applications crash

  • users get blank screens

  • debugging becomes difficult

  • unexpected behavior increases

Error handling improves:

  • application stability

  • debugging

  • user experience

  • security

Real World Importance

Imagine:

  • payment systems crashing silently

  • banking apps failing without messages

  • login systems breaking without explanation

That would create terrible user experience. Good applications handle failures gracefully.

Error Handling in APIs

Example:

try {
  const response = await fetch(url);
} catch (error) {
  console.log("API request failed");
}

Because:

  • internet may fail

  • server may go down

  • timeout may occur

Real applications must expect failures.

Common Types of JavaScript Errors

Some common error types:
SyntaxError Invalid JavaScript syntax.

ReferenceError

Using variables that do not exist.

TypeError

Using values incorrectly.

Example:

undefined.name

RangeError

Value goes outside allowed range.

Common Beginner Mistake

Many beginners write:

try {
  riskyCode();
}

without proper catch.

But:

  • errors should be handled meaningfully

  • not ignored silently

Good error messages make debugging easier.

Another Common Mistake

Some beginners overuse try...catch. Not every line needs it.

Usually:

  • risky operations

  • async operations

  • external data handling

are the most common places for error handling.

Understanding the Bigger Picture

Error handling is not just about preventing crashes. It is about:

  • creating reliable applications

  • improving debugging

  • handling failures gracefully

  • protecting user experience

Professional applications are built assuming:

things can fail anytime.

Final Understanding

Errors are situations where JavaScript cannot execute code properly.

Using:

  • try

  • catch

  • finally

  • throw

developers can safely handle failures and control application behavior. try...catch prevents applications from crashing unexpectedly, while custom errors help enforce rules and validations. And proper error handling is one of the biggest differences between beginner-level code and production-ready applications.

1 views