Finally, except if not!

MS docs say finally will always run even if you use exit keyword or press CTRL + C on keyboard to terminate script.

Seems like it’s not imune to return keyword:

try {
    throw 1
}
catch
{
    return "x"
} finaly { "fin" }

Output:

x

Expected:

x
fin

The documentation does not claim the finally block to be imune though.

And BTW: it’s finally with a double L !!! :wink:

1 Like

Now that’s funny, it works as expected when correctly spelled to “finally”.

But why the heck it didn’t error out for mispelling a language keyword? :upside_down_face:

Yes it does, it says finally will run no matter what.

I’d read that diffently …

Freeing resources using finally

To free resources used by a script, add a finally block after the try and catch blocks. The finally block statements run regardless of whether the try block encounters a terminating error. PowerShell runs the finally block before the script terminates or before the current block goes out of scope.

A finally block runs even if you use CTRL+C to stop the script. A finally block also runs if an Exit keyword stops the script from within a catch block.

It does not mention return at all.

You read it as if exit keyword is less impactful than return :wink:
Obviously there is no difference when it comes to how finally works.

Can you give an example where finally won’t run?

You claimed that it will not run when return is called. I just said that the documentation does not mention return explicitly … that’s all. :man_shrugging:t4:

How would you read it?

exit:

return:

that’s fine, I didn’t notice my finally was misspelled because there was no error but it should have errored IMO.

I guess it was interpreted as function name but it wasn’t called due to return preceding…

I read it as whole or what the docs are saying in whole rather than explicitly.
similar to how the bible is read :slightly_smiling_face:

Return exits immediately so maybe that’s why I’d didn’t error. But I’d also think it would catch that error at parsing (or while you’re editing it)

1 Like