JavaScript try...catch handles exceptions thrown while code in a try block is executing. Put only code you can meaningfully recover from or report inside try; the catch block receives the thrown value, usually an Error object.
Basic syntax:
try {
riskyOperation();
} catch (error) {
console.error(error.message);
}
Handling an exception prevents that exception from propagating further only if the catch block does not throw it again. It does not make every programming error safe to ignore.
The original page intentionally referenced an undefined variable. In modern code, the exception can be displayed in the console or a controlled UI message.
try {
console.log(mySum); // ReferenceError
} catch (error) {
console.error("There was an error:", error.message);
}
console.log("Execution can continue here");
Built-in errors normally provide useful properties such as name and message. Development tools may also expose a stack trace.
try {
JSON.parse("invalid JSON");
} catch (error) {
console.log(error.name);
console.log(error.message);
console.error(error);
}
The old tutorial used browser detection to choose between Firefox and Internet Explorer-specific error properties. That is no longer appropriate; use the standard error object rather than branching on browser names.
throw stops normal execution and sends a value to the nearest applicable catch handler. Although JavaScript allows throwing almost any value, throwing an Error object is usually better because it carries a standard name, message, and stack information.
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.error(error.message);
}
This updates the original example that threw a plain string.
Error: generic base error.TypeError: an operation or value has an inappropriate type or use.RangeError: a numeric value or parameter falls outside an allowed range.ReferenceError: code references an identifier that cannot be resolved.SyntaxError: parsing or syntax is invalid; it is also used by APIs such as JSON.parse() for invalid input syntax.URIError: URI encoding/decoding functions encounter an invalid sequence.AggregateError: represents multiple errors in APIs that aggregate failures.function checkNumber(value) {
if (typeof value !== "number") {
throw new TypeError("Expected a number");
}
if (value < 0 || value > 100) {
throw new RangeError("Number must be between 0 and 100");
}
return value;
}
try {
checkNumber(150);
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
The optional finally block runs after try/catch handling whether an exception occurred or not. It is useful for cleanup that must happen on both success and failure.
let resourceOpen = false;
try {
resourceOpen = true;
console.log("Using resource");
} catch (error) {
console.error(error);
} finally {
resourceOpen = false;
console.log("Cleanup complete");
}
return in finally: it can override a value returned or an exception thrown earlier. Avoid that pattern unless you have a very specific reason.If you do not need the error value, modern JavaScript allows catch without a parameter.
try {
JSON.parse(input);
} catch {
console.log("Input is not valid JSON");
}
A catch block should not silently absorb every failure. Handle errors you understand and rethrow unexpected errors so they remain visible to higher-level code or monitoring.
try {
processData();
} catch (error) {
if (error instanceof RangeError) {
console.warn("Value is outside the supported range");
} else {
throw error;
}
}
A try...catch catches exceptions thrown synchronously while execution is inside its try block. It does not reach forward into a later timer callback simply because the timer was scheduled from inside the try block.
try {
setTimeout(() => {
// An exception thrown here happens later, outside the outer try block.
console.log("Timer callback");
}, 0);
} catch (error) {
console.error(error);
}
Put error handling inside the asynchronous callback where appropriate, or use Promise/async error handling.
Inside an async function, an awaited rejected promise behaves like a thrown exception and can be handled with try...catch.
async function loadData() {
try {
const response = await fetch("/api/data");
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Unable to load data:", error.message);
throw error;
}
}
Without await, handle Promise rejections with .catch() or return the promise to a caller that handles it.
A nested catch can handle a local failure while an outer handler remains responsible for other errors.
try {
try {
JSON.parse("bad json");
} catch (error) {
console.warn("Local parse problem");
throw error;
}
} catch (error) {
console.error("Outer handler:", error.message);
}
throw can enforce a function's contract when invalid input means the function cannot continue normally.
function checkAge(age) {
if (!Number.isInteger(age)) {
throw new TypeError("Age must be an integer");
}
if (age < 18) {
throw new RangeError("You must be at least 18 years old");
}
return true;
}
For normal form feedback, validation results can also be returned without throwing. Use exceptions for exceptional failure paths rather than as a replacement for every branch.
If JavaScript cannot parse a script at all, the code may fail before the surrounding runtime flow can execute. However, APIs such as JSON.parse() can throw a SyntaxError at runtime and that exception can be caught normally.
try {
JSON.parse('{"name": }');
} catch (error) {
if (error instanceof SyntaxError) {
console.log("JSON text has invalid syntax");
}
}
The original page described old Firefox and Internet Explorer error-console behavior. Today, use the browser developer tools console and debugger rather than browser-name detection. For application-wide reporting, browsers also expose error and unhandled-rejection events, but those are not substitutes for handling recoverable errors close to where they occur.
try and then hiding every error.Error object would provide better diagnostic information.Continue with browser navigator information, alert dialogs, if...else, and functions.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.