Skip to main content

Does finally run if try has a return?

This is one of the most common "gotchas" in JavaScript! The answer is yes, the finally block always runs, even if try has a return inside it.


The general rule

Regardless of whether there was an error, there was a return, or there was a throw, the finally block is guaranteed to run before the function exits.


Example 1. return inside try

javascript
function test() { try { console.log("Inside try"); return "Value from try"; } finally { console.log("The finally block runs anyway"); } } console.log("Result:", test());

Output:

javascript
Inside try The finally block runs anyway Result: Value from try

You can see that:

  1. First, the code inside try runs.
  2. Then, before the value is returned, finally is called.
  3. Only after that does the function return its result.

Example 2. return and throw inside try

javascript
function example() { try { console.log("Before returning"); return "Return from try"; } catch { console.log("catch will not run"); } finally { console.log("finally runs anyway"); } } console.log(example());

Output:

javascript
Before returning finally runs anyway Return from try

Example 3. return and an error: finally still fires

javascript
function example() { try { throw new Error("Error in try"); } catch (e) { console.log("Caught:", e.message); return "Return from catch"; } finally { console.log("finally runs anyway"); } } console.log(example());

Output:

javascript
Caught: Error in try finally runs anyway Return from catch

Example 4. finally can override the return

If finally also has a return, it replaces the result that was returned from try or catch.

javascript
function example() { try { return "From try"; } finally { return "From finally"; } } console.log(example());

Output:

javascript
From finally

That's why adding a return inside finally is a bad practice: it makes the function's behavior unpredictable.


Example 5. finally runs even on an error

javascript
function example() { try { throw new Error("Error!"); } finally { console.log("finally fires even on an error"); } } example(); // Uncaught Error: Error!

Output:

javascript
finally fires even on an error Uncaught Error: Error!

Summary

ScenarioDoes finally run?What happens
No errorsYesAfter try
There is an errorYesAfter catch
There is a return in tryYesBefore the function exits
There is a return in catchYesBefore the function exits
There is a throwYesBefore the exception is thrown
There is a return in finallyYes, and it overrides the result

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.