During my #SPSNYC session on PowerShell basics a good question was asked about error handling (specifically the use of Try/Catch) which, as time was tight, I was only able to answer in the briefest possible way.
This prompted the inimitable Scott Hoag (@ciphertxt) to post to twitter what is surely a contender for “funniest 140 char geek joke” I’ve seen (added here for posterity…)
Ignoring the genius of this comedy, I felt the subject warranted a little more than the 30 seconds I gave it, so am using some time on a plane to spin up this quick post and a PowerShell script to go alongside and, hopefully, demo the concept in the context of SharePoint.
Try/Catch/Finally is actually a pretty simple concept:
- try – run the script elements within this block
- nice, safe bubble for running cmdlets that may fail
- catch – jump to this block (or blocks) if an error occurs in what you “try”
- bubble in which you can handle the error appropriately
- you can have multiple catch blocks which can be ordered by the nature of the error – see my PowerTip about this
- finally – jump to this block after try or catch regardless of whether an error was generated
- this block is really here to enable cleanup (such as object disposal)
- remember it runs regardless of the error state!
Essentially the script calls 3 functions, 4 times:
- generate an error with “-SilentlyContinue” set
- generate an error without “-SilentlyContinue”
- call a cmdlet successfully, without an error or catch
- call a cmdlet to generate an error thus invoking the catch
You can find the short demo script at http://bigseb.me/sebposh – it’s called “Start-DemoTryCatchFinally” and has (hopefully) enough commenting within to be self-explanatory…
There are a handful of things to note:
- The first function is really to make you think about using the “SilentlyContinue” ErrorAction. It has is uses for sure, but think about how and when you use it.
- Try/Catch will only work with Terminating errors – if you call a command that does not generate a terminating error you cannot “catch” it. Almost all cmdlets support the addition of “-ErrorAction Stop” to the suffix thus making it terminating, this is shown in the script.
- Clearly in the demo script a mickey mouse is being used, but it’s just for show – and as always; all the usual caveats apply.
more to follow…