Inconsistent error behavior

The different methods PowerShell exposes to terminate a script aren't entirely consistent and may lead to confused behavior.

When throw is used to raise a terminating error, it'll stop the current script and anything that called it. In the following example, child2 will never execute:

$ErrorActionPreference = 'Continue' 
function caller { 
    child1 
    child2 
} 
function child1 { 
    throw 'Failed' 
    'child1' 
} 
function child2 { 
    'child2' 
} 
caller 

When the ThrowTerminatingError method is used, processing within child1 stops, but the caller function continues. This is demonstrated as follows:

function caller { 
    child1 
    child2 
} 
function child1 { 
    [CmdletBinding()] 
    param ( ) 
 
    $errorRecord = [System.Management.Automation.ErrorRecord]::new( 
        [Exception]::new('Failed'), 
        'ID', 
        'OperationStopped', 
        $null 
    ) 
    $pscmdlet.ThrowTerminatingError($errorRecord) 
    'child1' 
} 
function child2 { 
    'child2' 
} 

Executing the caller function shows that child2 is executed:

child1 : Failed
At line:2 char:5
+ child1
+ ~~~~~~
+ CategoryInfo : OperationStopped: (:) [child1], Exception
+ FullyQualifiedErrorId : ID,child1
child2

The behavior of the preceding example is equivalent to the behavior seen when calling cmdlets. For example, the ConvertFrom-Json command raises a terminating error when the content it's asked to convert is invalid.

When a cmdlet throws a terminating error within another function, the caller script continues to execute unless ErrorAction is set to Stop. In the following example, ConvertFrom-Json will raise a terminating error, but won't stop the caller function:

function caller { 
    ConvertFrom-Json -InputObject '{{' 
    child1 
} 
function child1 { 
    'Called' 
} 
caller 

The same behavior is seen when calling .NET methods, shown as follows. The static method, IPAddress.Parse, will raise an exception because the use of the method isn't valid. The function continues on from this error and calls child1:

function caller { 
    [IPAddress]::Parse('this is not an IP') 
    child1 
} 
function child1 { 
    'Called' 
} 
caller 

The interaction between Throw and ErrorAction is explored in greater detail in the following section, which describes patterns for raising and handling errors.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.156