Skip to content

try/catch overrides $ErrorActionPreference? #5693

@narrieta

Description

@narrieta

I was very surprised that if the call to 'bar' is done from within try/catch, then its $ErrorActionPreference is ignored.

See the script below. When 'bar' is called errors are ignored as expected, but when doing it within try/catch the errors surface. Is this the expected behavior?

The script below is a simplification of my actual scenario; in my actual scenario 'foo', 'bar' and the call to 'bar' are on different modules/scripts.

function foo($i) {
    if ($i -eq 3) {
        throw 'error'
    }
}

function bar {
    $ErrorActionPreference = 'SilentlyContinue'

    for ($i = 0; $i -lt 5; $i++) {
        Write-Verbose -Verbose $i

        foo($i)
    }
}

Write-Verbose -Verbose 'No try/catch'

bar

Write-Verbose -Verbose ''

Write-Verbose -Verbose 'With try/catch' 

try {
    bar
} catch {
    Write-Verbose -Verbose $_
}  
 

VERBOSE: No try/catch
VERBOSE: 0
VERBOSE: 1
VERBOSE: 2
VERBOSE: 3
VERBOSE: 4
VERBOSE: 
VERBOSE: With try/catch
VERBOSE: 0
VERBOSE: 1
VERBOSE: 2
VERBOSE: 3
VERBOSE: error

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking-Changebreaking change that may affect usersIssue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aResolution-No ActivityIssue has had no activity for 6 months or moreWG-Enginecore PowerShell engine, interpreter, and runtime

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions