The real purpose of the Finally statement in PowerShell

When I learned PowerShell and discovered the try/catch/finally statements I was immediately puzzled by the usefulness of the Finally statement and I never found its real functional purpose clearly documented somewhere.

Useless usage of the Finally statement

Example with no error

Here is a first example with the finally statement.

try{
'Try'
}
catch{
'Catch'
}
finally{'Finally'}
'After finally'


And here is a second example without the finally statement.

try{
'Try'
}
catch{
'Catch'
}
'Finally'
'After finally'


As you can notice, there is no difference if you use the finally statement or not.

Example catching an error

Here is a first example with the finally statement.

try{
'Try'
1/0
}
catch{
'Catch'
}
finally{'Finally'}
'After finally'


And here is a second example without the finally statement.

try{
'Try'
1/0
}
catch{
'Catch'
}
'Finally'
'After finally'


Here again, you can notice that there is no difference if you use the finally statement or not.

Real usage of the finally statement

In fact, the finally statement becomes useful when you exit your script or function from inside the try or catch section with an exit or a break statement.

Example when exiting from inside the try

try{
'Try'
break
}
catch{
'Catch'
}
finally{'Finally'}
'After finally'


As you can notice, the finally section has been executed, but not the code after this section.

Example when exiting from inside the catch

try{
'Try'
1/0
}
catch{
'Catch'
break
}
finally{'Finally'}
'After finally'


Here again, you can notice that the finally section has been executed, but not the code after this section.

Conclusion

I am not sure there are a lot of cases where you want to exit your script or function from inside the try or catch section… However, at least now you know that if you don’t exit your code from inside those two sections, the finally statement has no utility.

But yes, if you really want to exit your code from inside the try or catch section, then you can use the finally section for a common code (to the Try and Catch section) when you need to do some “final” cleanup.

One thought on “The real purpose of the Finally statement in PowerShell

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s