Sunday, January 13, 2013

Catching Exceptions in PowerShell

In a recent class, I was discussing how you can deal with exceptions that occur when PowerShell hits a terminating error. Doing this allows you to gather information around events that should not have happened – but did! I wrote up a blog article a couple of years ago which describes error handling in PowerShell that describes how you can catch errors.

The question was not so much, how do I do it, but what are the specific errors you can actually trap. For example,

Trap [System.DivideByZeroException] { 'whoops - divide by zero'; }
$z = 0
1/$z
"next'

or

Try {
  $z = 0
  1/$z
}
Catch [System.DivideByZeroException] {
   
'whoops - divide by zero' }

That bit is fairly easy.  But do I what I can trap for? Turns out, answering that question is relatively easy as long as you know the .NET exception names you wish to trap or catch.  Within .NET, an Exception is a specific terminating error that I can explicitly catch. In the above code fragment, the code catches the specific Divide by Zero exception.

I have just posted a script to my PowerShell Scripts blog which does this. The script is posted at: http://pshscripts.blogspot.co.uk/2012/12/show-exceptionsps1.html. If you download it and run it, look in the right hand column - those are the exceptions you can catch.

To find more about the individual exceptions, MSDN is your friend.

No comments: