JavaScript Error Handling
# JavaScript Error Handling
No matter how good a programmer you are, your code will encounter errors. A server will go offline, a user will type a letter where a number should be, or you will accidentally misspell a variable name.
If JavaScript hits an error it doesn't know how to handle, it completely crashes and stops executing the rest of the script. This chapter teaches you how to catch those errors gracefully so your app stays alive.
1. Introduction
Error handling in JavaScript revolves around the try...catch statement.
The concept is simple: you tell JavaScript to try running a block of code. If an error occurs, instead of crashing the browser tab, JavaScript immediately jumps into the catch block, allowing you to handle the problem (like showing an error message to the user) and continue running the rest of your app.
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Use the
try...catchstatement to prevent app crashes.
-
Read and understand the
Errorobject.
-
Use the
finallyblock for cleanup operations.
-
Create custom errors using the
throwkeyword.
- Build a Safe JSON Parser mini-project.
3. The try...catch Syntax
---
4. Real-world Examples & Code Snippets
Example 1: A Standard Crash
Example 2: Catching the Crash
Example 3: The Error Object
The catch block automatically receives an object (usually named err or error) containing details about what went wrong. The most important property is error.message.
Example 4: The finally Block
The finally block is optional. It executes code AFTER try and catch, regardless of whether an error occurred or not. It is perfect for cleanup tasks, like hiding a "Loading" spinner.
Example 5: Custom Errors (throw)
Sometimes, JavaScript's built-in syntax rules are fine, but your *business rules* are broken. You can force an error using the throw keyword.
Example 6: Handling JSON Parsing Errors
JSON.parse() is notoriously dangerous. If the server sends corrupted JSON text, JSON.parse throws a SyntaxError and crashes your app. ALWAYS wrap it in try...catch.
Example 7: Handling fetch API Errors
When making web requests, use try...catch inside an async function (which we will learn in Chapter 28), or rely on .catch() for Promises.
---
5. Common Mistakes for Beginners
-
1.
Overusing
try...catch: Do not wrap your entire JS file in one massivetry...catch. Only wrap specific blocks of code that are inherently unpredictable (like JSON parsing, third-party API calls, or complex user inputs).
-
2.
Ignoring the Catch Block:
catch(e) { }with nothing inside is called "swallowing an error." The code fails silently, and you will have a nightmare trying to debug why your app isn't working. Always at leastconsole.error(e).
-
3.
Syntax Errors vs Runtime Errors:
try...catchonly catches Runtime errors (errors that happen while the code is running). It cannot catch Syntax errors (like forgetting a closing bracket}in your script), because the browser refuses to run the script at all.
6. Best Practices
-
Always validate inputs BEFORE trying to use them, rather than relying solely on
try...catchto catch bad inputs.
-
Use
throw new Error("msg")rather than justthrow "msg". Throwing a proper Error object provides a Stack Trace, which helps you debug exactly which line caused the error.
7. Mini Project: Safe JSON Parser
Let's build a UI that allows a user to paste JSON data and tries to format it. If the user pastes bad data, we catch the crash and show a friendly error on the screen.
HTML:
error.js:
8. Exercises
-
1.
Write a function
divide(a, b)that throws a custom Error ifbis0.
-
2.
Wrap a call to your
divide(10, 0)function inside atry...catchblock andconsole.logthe error message.
-
3.
Add a
finallyblock that logs "Calculation attempted".
9. MCQs (Multiple Choice Questions)
Q1: What happens if JavaScript hits a runtime error without a try...catch block?
A) It alerts the user.
B) It skips the line and continues.
C) The script execution halts completely.
D) It converts the error to a string.
*Answer: C*
Q2: Which block always runs regardless of whether an error occurred?
A) catch
B) try
C) throw
D) finally
*Answer: D*
Q3: Which keyword allows you to manually generate an error?
A) error
B) throw
C) catch
D) reject
*Answer: B*
10. Interview Questions
Q: What is a Stack Trace in JavaScript errors?
*A: When you generate a new Error object, it contains a property called .stack. This is a string that shows exactly the sequence of function calls that led to the error, and the exact line number where the error occurred. It is invaluable for debugging.*
11. FAQs
Q: Why doesn't try...catch work on setTimeout?
*A: try...catch is synchronous. If you put a setTimeout inside a try, the try block finishes instantly before the timeout triggers. When the timeout finally runs 2 seconds later and causes an error, it is no longer inside the try block. You must put the try...catch INSIDE the timeout callback.*
12. Summary
-
tryallows you to test a block of code.
-
catchallows you to handle the error if thetryblock crashes.
-
finallyallows you to run cleanup code regardless of success or failure.
-
throw new Error("msg")lets you create custom business-logic errors.
-
Never parse JSON without wrapping it in
try...catch.
13. Next Chapter Recommendation
We just mentionedsetTimeout. Dealing with time is a huge part of JavaScript. In the next chapter, JavaScript Timers and Intervals, we will learn how to delay execution, repeat functions, and build stopwatches.