Back to Library
Region:
Switch to ID
Advanced freeCodeCamp • lecture-debugging-techniques
How Does Try...Catch...Finally Work?
Lesson Overview
The `try...catch...finally` statement in JavaScript is used to handle runtime errors gracefully, preventing your application from crashing when something goes wrong.
The try...catch...finally statement in JavaScript is used to handle runtime errors gracefully, preventing your application from crashing when something goes wrong.
How it works:
tryblock: You place the code that might throw an error inside this block. It acts as a “safe zone” for code that could potentially fail.catchblock: If an error occurs within thetryblock, execution immediately stops and jumps to thecatchblock. Thecatchblock receives an error object containing details about what went wrong, allowing you to handle the error or log it appropriately.finallyblock: This block executes regardless of whether an error occurred or not. It is primarily used for cleanup tasks that must happen whether the operation succeeded or failed (e.g., closing a database connection, stopping a loading spinner, or resetting state).
Basic Example:
try {
console.log("Attempting to do something...");
// Simulate an error
throw new Error("Something went wrong!");
} catch (error) {
// Handle the error
console.error("Caught an error:", error.message);
} finally {
// This always runs
console.log("Cleanup: Operation finished.");
}
Key Points:
- Graceful Handling: Instead of the entire program crashing, you can intercept the error and keep the application running.
finallyis optional: You can usetry...catch,try...finally, ortry...catch...finally.- Caution with
finally: Be careful usingreturnorthrowstatements inside afinallyblock, as they can override any return values or errors that occurred in thetryorcatchblocks. - Runtime Errors vs. Syntax Errors:
try...catchhandles runtime errors (exceptions that occur while code is running). It generally cannot catch parse-time/syntax errors because those prevent the code from being interpreted in the first place.