JavaScript Error Handling Interview Questions and Answers
Understand Error objects, try/catch/finally, throwing errors, and reliable failure handling.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
Theoretical JavaScript Interview Questions
An error in JavaScript is something that goes wrong while the code runs. Without proper handling, it stops the normal flow of your program. JavaScript has a built-in Error object that carries information about what went wrong, including a message and the type of error.
console.log(undeclaredVariable); // ReferenceError: undeclaredVariable is not defined
The try block contains code that might throw an error. If something goes wrong, JavaScript jumps to the catch block instead of crashing the whole program. The catch block receives the error object so you can handle it properly.
try {
let result = JSON.parse("invalid json");
} catch (error) {
console.log("Something went wrong:", error.message);
}
The finally block runs no matter what. Whether the code in try succeeds or throws an error, finally always runs. It is great for cleanup tasks like closing a connection or hiding a loading spinner.
try {
fetchData();
} catch (error) {
console.log("Error:", error.message);
} finally {
hideLoadingSpinner(); // runs whether fetchData succeeded or failed
}
JavaScript has several built-in error types:
- SyntaxError - code with invalid syntax that cannot be parsed (usually a typo)
- ReferenceError - trying to use a variable that was never declared
- TypeError - using a value in a way that does not match its type (e.g. calling something that is not a function)
- RangeError - a value is outside of an allowed range
- URIError - a malformed URI passed to functions like
decodeURI() - EvalError - related to the
eval()function (you will rarely see this one)
null.toString(); // TypeError
undeclaredVar; // ReferenceError
new Array(-1); // RangeError
return exits a function and sends a value back to the caller. throw also stops execution but it signals that something went wrong. The thrown value (usually an Error object) travels up the call stack until it hits a catch block. If it never does, it crashes the program.
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero"); // signals failure
return a / b; // normal exit
}
You use .catch() at the end of a Promise chain to catch rejected promises. You can also pass a second argument to .then(), but that only catches errors from that specific step. Using .catch() at the end is cleaner and catches errors from any step in the chain.
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log("Request failed:", error.message));
A try block runs code that may throw, and catch receives a thrown value if an exception occurs. They handle synchronous exceptions; rejected promises need a rejection handler or await inside try.
Place the await expression inside a try block and handle its rejection in catch. Without a catch or another rejection handler, the rejection may be unhandled.
Yes. finally runs as control leaves try/catch, including when a return is pending or an exception is propagating; a return or throw in finally can override that result.
Create a descriptive Error and pass the original in the cause option, such as new Error('Operation failed', { cause: error }). This preserves the lower-level failure for diagnostics.
catch is equivalent to then(undefined, handler). If its handler returns normally the chain fulfills with that value; if it throws or returns a rejection, the chain remains rejected.
Handle an error where recovery or useful reporting is possible, preserving context and avoiding empty catch blocks that hide failures. A layer that cannot recover should generally let its caller decide policy.
JavaScript Practical and Coding Interview Questions
Problem: Create an InvalidAgeError class and a function that throws it when an age is below 18. Catch it and log its name and message.
class InvalidAgeError extends Error {
constructor(age) {
super('Age must be at least 18; received ' + age);
this.name = 'InvalidAgeError';
}
}
function checkAge(age) {
if (age < 18) throw new InvalidAgeError(age);
return 'Allowed';
}
try {
console.log(checkAge(16));
} catch (error) {
console.log(error.name + ': ' + error.message);
}Problem: Create parseOr(text, fallback), which parses JSON and returns fallback on invalid input. Demonstrate valid and invalid input.
function parseOr(text, fallback) {
try { return JSON.parse(text); }
catch (error) { return fallback; }
}
console.log(parseOr('{"ok":true}', null));
console.log(parseOr('not JSON', { ok: false }));Problem: Implement divide(a, b) that throws TypeError for invalid numeric arguments and RangeError for a zero divisor. Catch and print the error from divide(10, 0).
function divide(a, b) {
if (typeof a !== 'number' || typeof b !== 'number' || !Number.isFinite(a) || !Number.isFinite(b)) throw new TypeError('Arguments must be finite numbers');
if (b === 0) throw new RangeError('Divisor must not be zero');
return a / b;
}
try { console.log(divide(10, 0)); }
catch (error) { console.log(error.name + ': ' + error.message); }