try/catch
In one line
try/catch is a construct that lets you attempt code that may throw an error and handle it gracefully instead of crashing.
In simple words
try/catch is how you handle errors in JavaScript. Code in the try block runs normally. If it throws an error, execution jumps to the catch block with the error object. If no error occurs, catch is skipped.
An optional finally block runs regardless of whether an error occurred — even if return is called in try or catch. This makes it ideal for cleanup (closing files, releasing resources).
In async functions, try/catch catches rejected Promises when used with await. Without async/await, use .catch() on the Promise chain. Always handle errors to avoid unhandled rejections and crashes.
Example
try {
const data = JSON.parse("invalid json");
} catch (err) {
console.log("Parse failed:", err.message);
} finally {
console.log("Cleanup runs always");
}try runs the code, catch handles errors, finally always runs.
Related terms
Related Resources
Related Lessons
- Functions
Learn about try/catch.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.