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
Olaf
December 18, 2022, 10:17pm
2
The documentation does not claim the finally block to be imune though.
metablaster:
} finaly { "fin" }
And BTW: it’s finally with a double L !!!
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?
Yes it does, it says finally will run no matter what.
Olaf
December 18, 2022, 10:57pm
4
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
Obviously there is no difference when it comes to how finally works.
Can you give an example where finally won’t run?
Olaf
December 18, 2022, 11:31pm
6
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.
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…
Olaf:
How would you read it?
I read it as whole or what the docs are saying in whole rather than explicitly.
similar to how the bible is read
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)