$Error variable is $Null but $_ contains error in Catch

Question:

I have PS module that contains a number of scripts for individual functions. There is also a “library” script with a number of helper functions that get called by the functions used in the module.

Let’s call the outer function ReadWeb, and it uses a helper function ParseXML.

I encountered an issue this week with error handling in the inner helper ParseXML function. That function contains a try/catch, and in the catch I interrogate:

$Error[0].Exception.InnerException.Message

…in order to pass the error back to the outer scope as a variable and determine if ParseXML worked.

For a particular case, I was getting an indexing error when I called ReadWeb. The root cause turned out to be the $Error object in the Catch block in ParseXML was coming back $Null.

I changed the error handling to check for a $Error -eq $Null and if it is, use $_ in the Catch to determine what the error message is.

My question is: what would cause $Error to be $null inside the Catch?

Answer:

Edit: answer based on Powershell 3.

$error is an automatic variable handled by Powershell: 3rd § of the LONG DESCRIPTION in about_Try_Catch_Finally.

It is considered as the context of the Catch block, thus being available as $_.
Since Catch block is a different block than Try, the $error automatic variable is reset and valued $null.

Source:

$Error variable is $Null but $_ contains error in Catch by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply