Error Handling
In real life, things don’t always go as planned. A network request can fail, user input can be wrong, or data might be missing.
In JavaScript, error handling helps us deal with such situations gracefully instead of crashing the application.
What Is an Error?
An error occurs when JavaScript encounters something it cannot understand or execute.
Without proper handling, errors can stop the program and create a bad user experience.
Types of Errors (Beginner View)
- Syntax errors – mistakes in code structure
- Runtime errors – errors while the program is running
- Logical errors – code runs but gives wrong output
At this stage, we focus on handling runtime errors safely.
The try...catch Statement
JavaScript provides try...catch to catch errors
and prevent the program from stopping.
try {
let result = totalPrice / items;
console.log(result);
} catch (error) {
console.log("Something went wrong");
}
If an error occurs inside try,
JavaScript jumps to catch.
Using the Error Object
The catch block receives an error object
that contains information about what went wrong.
try {
console.log(value);
} catch (error) {
console.log(error.message);
}
This helps during debugging and logging.
The finally Block
The finally block runs no matter what —
whether an error occurs or not.
try {
console.log("Processing...");
} catch (error) {
console.log("Error occurred");
} finally {
console.log("Process completed");
}
This is useful for cleanup actions.
Real-World Example
Imagine fetching user data from an API:
try {
let user = JSON.parse(data);
console.log(user.name);
} catch (error) {
console.log("Invalid data received");
}
Error handling ensures the app doesn’t break when unexpected data appears.
Common Beginner Mistakes
- Ignoring errors completely
- Using
try...catcheverywhere unnecessarily - Displaying technical errors to users
Handle errors clearly but show friendly messages to users.
Thumb Rules
- Use
try...catchfor risky operations - Log errors for debugging
- Show user-friendly messages
- Never assume everything will work perfectly
More on Error Handling Later
This lesson introduced basic error handling concepts.
More advanced techniques are covered later.
- Error handling with asynchronous code is covered in Lesson 33 (Async / Await)
- API error handling is explored in Lesson 49 (Async API Integration)
What Comes Next?
Now that you can handle errors safely, it’s time to interact with the browser.
In the next lesson, we will learn about the DOM.