Search This Blog

Mar 8, 2012

[Powershell] Try-Catch fails to catch an exception?

I was running a script that does WMI query and found that my try-catch-final statement seemed not working. The exception was still shown on console instead of handled by my catch block.

It turns out that exceptions are categorized into two groups, terminating exceptions and non-terminating exceptions. By default, try-catch intercepts only terminating exceptions. No surprisingly, get-WMIobject exceptions are non-terminating exceptions.

There are two ways to make it work. One is to make all exception terminating by below assignment:

$ErrorActionPreference = "Stop"; #Make all errors terminating


Remember to reset the preference at the end of your script as this is global.


$ErrorActionPreference = "Continue"


Or right after get-WMIobject statement, check the value of $?


if ($?){ 
        #processing block
}
else {
       throw $error[0].exception
}