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
tryandcatchUnderstanding the
finallyblockThrowing 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:
console.log(userName);
Output:
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
const user = null;
console.log(user.name);
Output:
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:
trycatch
to handle errors safely.
Basic Syntax
try {
// code that may cause error
} catch (error) {
// code to handle error
}
How It Works
JavaScript runs code inside
tryIf no error occurs → everything runs normally
If an error occurs → execution jumps to
catchThe error gets handled safely
First Example of try and catch
try {
console.log(userName);
} catch (error) {
console.log("Something went wrong");
}
Output:
Something went wrong
Instead of crashing, the program handles the error gracefully.
Accessing the Error Object
The catch block receives an error object.
Example
try {
console.log(userName);
} catch (error) {
console.log(error);
}
Output may look like:
ReferenceError: userName is not defined
Useful Error Properties
| Property | Meaning |
|---|---|
error.name |
Type of error |
error.message |
Error description |
Example
try {
console.log(userName);
} catch (error) {
console.log(error.name);
console.log(error.message);
}
Output:
ReferenceError
userName is not defined
Error Handling Flow Diagram
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
catchruns or not
Syntax
try {
// code
} catch (error) {
// handle error
} finally {
// always runs
}
Example
try {
console.log("Inside try block");
} catch (error) {
console.log("Inside catch block");
} finally {
console.log("Finally block executed");
}
Output:
Inside try block
Finally block executed
Example with Error
try {
console.log(userName);
} catch (error) {
console.log("Error handled");
} finally {
console.log("Finally always runs");
}
Output:
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
Try Block
│
├── Error? ── No ──► Finally
│
└── Yes
│
▼
Catch
│
▼
Finally
Throwing Custom Errors
JavaScript allows developers to create their own errors using:
throw
This is useful when validating data or enforcing rules.
Basic Example
throw new Error("Something went wrong");
Example with try and catch
try {
throw new Error("Invalid password");
} catch (error) {
console.log(error.message);
}
Output:
Invalid password
Real-World Validation Example
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:
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
const number = 10;
number.toUpperCase();
Output:
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:
catch (error) {}
Always log or handle errors meaningfully.
3. Throwing Strings Instead of Error Objects
Avoid:
throw "Something went wrong";
Prefer:
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
Create a variable
ageIf age is less than 18, throw custom error
Handle error using
tryandcatchAdd a
finallyblock
Example Solution
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.
