1. Introduction
The try...catch...finally statement is JavaScript's core construct for handling exceptions locally instead of letting them crash the program. Code that might fail goes inside try; recovery logic goes inside catch; and cleanup logic that must run regardless of success or failure goes inside finally.
Cricket analogy: try-catch-finally is like attempting a risky reverse sweep in try, having a recovery plan in catch if you're bowled out, and walking back to the pavilion in finally regardless of whether the shot succeeded or failed.
2. Syntax
try {
// code that may throw
} catch (error) {
// handle error
} finally {
// always runs
}
// catch binding is optional (ES2019+)
try {
riskyOperation();
} catch {
console.log("Something went wrong");
}3. Explanation
Execution enters the try block first. If no error is thrown, the catch block is skipped entirely and control moves to finally (if present). If an error is thrown anywhere inside try — including inside a function it calls — execution jumps immediately to catch, with the thrown value bound to the catch parameter. After catch finishes (or if there was no error), finally runs last, before control leaves the whole statement.
Cricket analogy: If the reverse sweep in try goes clean, execution skips catch and heads straight to walking off in finally; if it's caught out anywhere in the shot — even mid-swing — play jumps to catch with the dismissal recorded, then finally still runs, sending the batsman off regardless.
Since ES2019, the catch parameter is optional: catch { ... } is valid when you don't need to inspect the error object itself, just that something failed.
Cricket analogy: Since a rule change, a fielder can simply signal 'dropped catch' in catch { } without needing to log exactly which finger it slipped off — sometimes you just need to know something went wrong, not the full detail.
finally always runs, even if try or catch contains a return, throw, break, or continue. If finally itself contains a return, it overrides any return value from try or catch — this is a common source of subtle bugs, so avoid returning from finally unless intentional.
4. Example
function testFinally() {
try {
console.log("try block");
return "from try";
} catch (err) {
console.log("catch block");
return "from catch";
} finally {
console.log("finally block");
}
}
console.log("Result:", testFinally());
try {
JSON.parse("{ invalid json }");
} catch (err) {
console.log("Parse failed:", err.name);
} finally {
console.log("Parsing attempt complete");
}5. Output
try block
finally block
Result: from try
Parse failed: SyntaxError
Parsing attempt complete6. Key Takeaways
tryruns first;catchonly runs if an error is thrown insidetry.finallyalways executes — on success, on error, and even whentry/catchcontainreturn.- The catch parameter is optional since ES2019:
catch { ... }. - A
returninsidefinallysilently overrides areturnfromtryorcatch— avoid it unless intentional. - try-catch only handles synchronous errors in the block it wraps, not errors from callbacks scheduled later.
Practice what you learned
1. In what order do the blocks execute when `try` succeeds without throwing and a `finally` block is present?
2. If `try` contains `return 'A'` and `finally` contains `return 'B'`, what does the function return?
3. Since which JavaScript version can you write `catch { ... }` without a parameter?
4. Does `finally` run if `try` throws an error and `catch` is not present at all (only try-finally)?
5. What is bound to the catch parameter when an error is thrown?
Was this page helpful?
You May Also Like
Error Handling in JavaScript
How JavaScript represents runtime failures with Error objects and the built-in TypeError, RangeError, ReferenceError, and SyntaxError types.
Custom Errors in JavaScript
Building your own Error subclasses by extending the built-in Error class to represent domain-specific failures.
async/await in JavaScript
Learn how async/await provides synchronous-looking syntax for working with Promises, including error handling with try/catch.
Callbacks and Asynchronous JavaScript
Learn how JavaScript handles operations that take time using callback functions, and why deeply nested callbacks lead to callback hell.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics