Forget the "Finally"-Block

by Oct 14, 2011

When you handle errors using try/catch/finally, you may wonder what the finally block is for. Here is a demo:

try {
  dir nonexisting:\ -ErrorAction Stop
}
catch {
  "Error Occured: $_"
}
finally {
  'Doing Cleanup'
}

Whenever a non-terminating error is raised in the try-block, the error can be handled in the catch-block. The finally-block always executes, whether the try-block encountered an error or not. So actually, you could have placed that code outside the finally-block as well and omit it:

try {
    dir nonexisting:\ -ErrorAction Stop
}
catch {
    "Error Occured: $_"
}
'Doing Cleanup'

Twitter This Tip!
ReTweet this Tip!