JavaScript Error Handling — Interview Questions & Answers
Ques: What is error handling in JavaScript?
Ans: Error handling means writing code to detect, handle, and recover from unexpected situations (errors) during execution — such as invalid input, missing files, or network failures.
Ques: What are the main types of errors in JavaScript?
| Type | Description | Example |
|---|---|---|
| Syntax Error | Mistake in code syntax | if (true { |
| Reference Error | Using undefined variable | console.log(x); |
| Type Error | Using wrong type of value | null.toString() |
| Range Error | Number out of allowed range | new Array(-1) |
| URI Error | Malformed URI | decodeURI("%") |
| Eval Error | Issue with eval() (rare) | eval('bad code') |
Ques: What is the difference between syntax and runtime errors?
| Type | Checked When | Example |
|---|---|---|
| Syntax Error | Before execution (compile-time) | Missing ) |
| Runtime Error | During execution | Accessing undefined variable |
Ques: What is the purpose of try...catch?
Ans: Used to handle errors without stopping program execution.
try {
let result = x / 2; // x not defined
} catch (error) {
console.error("Error caught:", error.message);
}
Ques: How does finally work in error handling?
Ans: finally runs always, whether an error occurs or not — typically used for cleanup tasks.
try {
console.log("Trying...");
throw new Error("Oops!");
} catch (e) {
console.log("Caught error:", e.message);
} finally {
console.log("Always runs (cleanup)");
}
Ques: Can we have try without catch?
Ans: Yes, a try block can be followed by finally only if you don’t need to handle the error but still need cleanup.
try {
openFile();
} finally {
closeFile();
}
Ques: What is the throw statement used for?
Ans: Used to manually generate an error when a condition fails.
function divide(a, b) {
if (b === 0) throw new Error("Division by zero!");
return a / b;
}
try {
console.log(divide(5, 0));
} catch (e) {
console.log(e.message);
}
Ques: What values can be thrown in JavaScript?
Ans: You can throw any type (though best practice is to throw Error objects).
throw "string error";
throw 404;
throw { message: "Custom error" };
throw new Error("Something went wrong!");
Ques: What is the best practice when throwing errors?
- Always throw instances of the
Errorobject for consistency. - Include a meaningful
message. - Use specific custom error classes when necessary.
Ques: What are custom errors in JavaScript?
Ans: Custom errors are user-defined error types created by extending the Error class.
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Invalid email format!");
} catch (e) {
console.log(e.name + ": " + e.message);
}
Ques: Why use custom errors?
- To provide clearer error categorization
- To handle different error types differently
- For better debugging and logging
Ques: What properties does the Error object have?
| Property | Description |
|---|---|
name | Type of error (Error, TypeError, etc.) |
message | Description of the error |
stack | Stack trace (debug info) |
Example:
try {
throw new TypeError("Wrong type!");
} catch (e) {
console.log(e.name); // TypeError
console.log(e.message); // Wrong type!
console.log(e.stack); // Stack trace
}
Ques: What is the stack property used for?
Ans: It provides a trace of function calls that led to the error — helpful for debugging.
Ques: How do you handle errors in asynchronous code (callbacks)?
Ans: Always pass error as the first argument in callbacks.
fs.readFile("file.txt", (err, data) => {
if (err) return console.error(err);
console.log(data);
});
Ques: How to handle errors in Promises?
fetch("invalid-url")
.then(res => res.json())
.catch(err => console.log("Error:", err));
Ques: How to handle errors using async/await?
async function getData() {
try {
const res = await fetch("invalid-url");
const data = await res.json();
} catch (error) {
console.log("Caught async error:", error.message);
}
}
Ques: What happens if you don’t catch a rejected Promise?
Ans: It results in an “UnhandledPromiseRejectionWarning”, and in modern JS, it can crash your app.
Ques: Can catch handle syntax errors?
Ans: No, Syntax errors are detected before execution, so try...catch cannot handle them.
Ques: Can you nest try...catch blocks?
Ans: Yes, inner errors can be caught separately.
try {
try {
throw new Error("Inner error");
} catch (e) {
console.log("Inner caught");
throw e; // rethrow
}
} catch (e) {
console.log("Outer caught");
}
Ques: What does “rethrowing” mean in JS?
Ans: You can rethrow an error from a catch block to pass it up the chain.
Ques: Is try...catch blocking or asynchronous?
Ans: try...catch is synchronous — it only catches errors that happen inside the same call stack, not inside async callbacks.
Ques: How to catch errors globally in the browser?
window.onerror = function(message, source, lineno, colno, error) {
console.log("Global Error:", message);
};
Ques: How to catch unhandled promise rejections globally?
window.addEventListener("unhandledrejection", e => {
console.error("Unhandled Promise Rejection:", e.reason);
});
Ques: What’s the difference between Error, EvalError, and RangeError?
| Error Type | When It Occurs |
|---|---|
Error | Generic base class |
EvalError | When eval() fails |
RangeError | When a value is out of range |
