Skip to content

How, exactly, does PowerShell decide whether .ThrowTerminatingError() terminates only the statement? #6098

Closed
@alx9r

Description

@alx9r

Consider the following code:

function a {
    param ( [Parameter(ValueFromPipeline)]$x )
    process {
        $PSCmdlet.ThrowTerminatingError(
            [System.Management.Automation.ErrorRecord]::new(
                'exception message',
                'errorId',
                [System.Management.Automation.ErrorCategory]::InvalidOperation,
                $null
            )
        )
    }
}

Invoking

a
Write-Host 'statement after'

outputs

a : exception message
At C:\test1.ps1:15 char:1
+ a
+ ~
+ CategoryInfo          : InvalidOperation: (:) [a], Exception
+ FullyQualifiedErrorId : errorId,a

statement after

which seems to be consistent with .ThrowTerminatingError() resulting in a "statement-terminating error".

On the other hand, invoking

try
{
    a
    Write-Host 'statement after'
}
catch
{
    Write-Host 'catch'
}

outputs catch which indicates that, in this case, .ThrowTerminatingError() terminates more than just the statement.

What is happening with flow of control in the code with the try{} block? Does PowerShell search the whole call stack for a try{}catch{}? Are there circumstances aside from a wrapping try{} that results in .ThrowTerminatingError terminating more than just the statement?

FWIW, this arose trying to understand MicrosoftDocs/PowerShell-Docs#1583.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Issue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-AnsweredThe question is answered.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions