JavaScript Error Handling Guide: try, catch, finally & throw
Direct Answer & Key Concept
Error handling in JavaScript allows developers to anticipate runtime exceptions, intercept errors gracefully using try...catch...finally blocks, and throw custom Error instances without crashing the application.
// Robust Error Handling Example
function safeJsonParse(jsonString, fallback = {}) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.warn("JSON Parse Warning:", error.message);
return fallback;
} finally {
console.log("Parse attempt completed");
}
}
const valid = safeJsonParse('{"user": "Alex"}');
console.log("Valid:", valid); // { user: "Alex" }
const invalid = safeJsonParse('Invalid { JSON }', { default: true });
console.log("Fallback:", invalid); // { default: true }What is Error Handling in JavaScript?
Runtime errors occur when valid code encounters unexpected conditions—such as invalid JSON payloads, network connection drops, or operations on null properties. Without defensive error handling, an uncaught exception halts script execution and destabilizes the web application.
JavaScript provides structured exception handling via the try...catch...finally statement and the throw keyword.
The try, catch, and finally Anatomy
try {
// Code that might throw an exception
const data = JSON.parse(rawUserInput);
processData(data);
} catch (error) {
// Executed only if an exception was thrown in the try block
console.error("Parsing failed:", error.message);
} finally {
// Always executed regardless of whether an error occurred
cleanupResources();
}
1. The try Block
Encloses code that carries a risk of runtime failure. If no exceptions occur, the catch block is completely bypassed.
2. The catch Block
Catches thrown errors. In modern JavaScript (ES2019+), optional catch binding allows omitting the error parameter if it is not needed: catch { ... }.
3. The finally Block
Guaranteed to execute regardless of whether the try block completed cleanly or threw an error, making it ideal for closing database connections, stopping loading spinners, or clearing file handles.
Throwing Custom Errors
You can create and throw custom exceptions using the built-in Error constructor:
function calculateDiscount(price, percentage) {
if (typeof price !== "number" || price < 0) {
throw new TypeError("Price must be a positive number");
}
if (percentage < 0 || percentage > 100) {
throw new RangeError("Percentage must be between 0 and 100");
}
return price * (1 - percentage / 100);
}
Standard JavaScript built-in error types include TypeError, RangeError, SyntaxError, and ReferenceError.