63

This is a very basic question. In Java I use the finally statement to close resources because "it's a good practice". I've been developing in Javascript and then in Node.js during some years and I've never used the finally statement. I know that in Node.js all of us follow the first parameter error handling pattern. Anyway, the 2 following snippets do the same:

try{
    throw 123
}catch (e){

}finally{
    console.log(1)
}

.

try{
    throw 123
}catch (e){

}

console.log(1)

Both print 1.

Why is finally a keyword if it has no real benefit? The clean up code can be put inside the catch.

2
  • 7
    I don't believe this is a duplicate. The linked question is tagged as Java and this one is about JavaScript. The answers happen to be the same but marking it as a duplicate suggests that Java and JavaScript is the same, which they quite clearly aren't. Apr 20, 2018 at 10:40
  • 1
    "The clean up code can be put inside the catch." - No. The cleanup code must run both when the code in the try block completes successfully and when it throws.
    – axiac
    Jun 30, 2019 at 8:11

9 Answers 9

61

finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.

Just a simple and straightforward example that shows the difference. There is a return that breaks the function completion, but the console.log in finally is called while the last console.log is skipped.

let letsTry = () => {

  try {
    // there is a SyntaxError
    eval('alert("Hello world)');
    
  } catch(error) {
    console.error(error);
	
    // break the function completion
    return;
  } finally {
      console.log('finally')
  }

  // This line will never get executed
  console.log('after try catch')
}

letsTry();

2
  • If a programmer knows enough to use finally the chances are pretty slim they'd add an erroneous return in the catch ....
    – Drenai
    May 12, 2022 at 20:56
  • 15 years of code. I can finally check this question. Thx.
    – dagatsoin
    May 18, 2022 at 14:50
41

But try this:

try {
    throw "foo"
} catch (e) {
    throw "bar"
} finally {
    console.log("baz")
}

console.log("quux")

If a second error is thrown from within the catch block, the code after the try...catch block will not run.
The finally block will always run, even if there is an error in the catch block.

Furthermore, the finally block runs even if a return or break statement stops the code in the try or catch block. return statements in the finally block override return statements in the try or catch block.

function foo() {
    try {
        return "bar";
    } finally {
        return "baz";
    }
}

foo() // "baz"
1
3

the finally block is meant for a special purpose.

finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Since it wont effect your business logic,Still it's compiler friendly,In memory aspects.

2

oracle docs provide a good answer to this. Bottom line: finally gets called always! Even when you catch only one kind of exception (not the global catch), then finally gets called (after which your application probably breaks if there is no other catch)

2
  • 2
    Can you do that in javascript?
    – JNF
    Jun 23, 2015 at 7:08
  • 5
    Oracle docs are irrelevant here. This is a JavaScript question, not a Java question. You can’t, currently, use more than one catch in a Try statement, so how many kinds of exceptions you catch is irrelevant. I don’t think “global catch” is a thing in JS. Jun 27, 2021 at 1:33
2

What if the try-block returns early or throws an exception that you don't handle? You would still want to free the resources you have allocated, right?


EDIT:

The answers to the question seem almost philosphical, there is some 'guessing' and basically 'we believe it should be useful, because it is there, so it should have a use', and 'even Oracle says so'. Or maybe it is there to help the programmer not 'to forget something' or 'accidently exit and not realize it'.

These are almost all valid reasons, but there is also a technical reason.

It helps avoiding code duplication in the cases mentioned, where (a) either the try or one of the catch blocks returns or (b) if within the catch block a second exception is thrown.

In these cases, if some cleanup code or any other code that still needs to be executed after the return and after the second exception, could be placed into the finally block, if it is to be executed both after the try and after the catch block.

You could still do it without the finally block, but the code would have to be duplicated, which the finally block allows you to avoid. This is where you really need it.

So if you are sure you do not miss it as a case of (a) or (b) you could still put the 'finally' code after the try/catch block and omit the finally clause.

But what if the situation changes? When you or another person change the code at some later point it could be forgotten to check if the cleanup code is now skipped in some situation.

So why not always put the cleanup code inside the finally block? And this is what is recommended and what many JavaScript programmers do.

2

The problem is with your example. There are cases when you don't want to catch the exception.

try {
    if (Math.random() > 0.5) throw 123
}
finally {
    console.log(1)
}

In these cases all you could do is rethrowing the exception if you don't want to use finally.

try {
    if (Math.random() > 0.5) throw 123
}
catch (e) {
    console.log(1)
    throw e
}
console.log(1)

or maybe

try {
    if (Math.random() > 0.5) throw 123
    console.log(1)
}
catch (e) {
    console.log(1)
    throw e
}

Both alternative solutions lead to code duplication, that's why you need the finally keyword. It is used most of the time to free up unused resources. Forgetting about it may lead to unwanted locks or connections or memory leaks. I guess in some cases even a smart GC cannot prevent it.

0

You use it when you want to be sure your code is executed at the end, even if there was an exception during execution :

InputStream is = new FileInputStream("C://test.txt");
try {
    //code...
} catch (Exception e) {
    //code...
} finally {
    is.close();
}
2
  • almost, it will also execute if you return something in the catch block Jan 23, 2019 at 23:16
  • 2
    This does not answer the question and is not even Javascript-related at all
    – phil294
    Jul 28, 2019 at 16:39
0

This is a very good question.

There is little to no reason to use finally in javascript, but I can imagine situations where it could be of practical use.

Suppose you have a webpage where you show a certain div after some user action, e.g. button clicked.
The div shows some logging for instance for the action the user requested.
After the action is complete (error or no error), you want to be sure to hide the div again. For that you can use the finally clause.

function doSomething() {
    var d = document.getElementById("log");
    show(d);
    try {
        ... execute action ...
    } catch(e) {
        log(e);
    } finally {
        hide(d);
    }
}

In general, as you mentioned, exceptions are less and less used in JavaScript in favor of error callbacks.
So, one could as well ask, what good uses are for exceptions in JavaScript in general.

1
  • 3
    In your example why not just call hide(d) after the catch block, instead of inside a finally. Either way the code will run through the try/catch and then run hide(d), so there doesn't seem to be any point to using finally? Jul 11, 2018 at 21:26
-3

In Java, if there's an Exception thrown that is not matched by any of the catch-blocks execution will break and any open resources will be left open. The finally block will always be executed, even if an uncaught exception occurs.

1
  • 8
    This question is about JavaScript
    – mit
    Jul 7, 2018 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.