Skip to content

Why do handled exceptions show in ErrorVariable? #3768

@Jaykul

Description

@Jaykul

When you use try/catch and handle an exception, it still shows up in the global $Error, and more importantly, in the ErrorVariable.

Is there any way to actually prevent handled exceptions from leaking into the ErrorVariable? Is there any way for a caller to determine that they are not, in fact, errors, but expected results that were dealt with by the function? That is, how does a caller distinguish the errors that matter?

Consider a simple example:

function Count-Parameters {
    [CmdletBinding()]
    param([Parameter(ValueFromRemainingArguments)]$Parameters)
    try {
        $Parameters.FasterMethod()
    } catch {
        $Parameters.Count
    }
}

$Count = Count-Parameters # Everything is fine

$Count = Count-Parameters This One Has Four # Still fine

# But then my paranoid "best practice" fanatic does something like this:
$Count = Count-Parameters -ErrorVariable noCount
if(!$Count -and $NoCount) { 
   Write-Warning $noCount
}

How can I stop the error variable from containing these things that I explicitly handled?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking-Changebreaking change that may affect usersCommittee-ReviewedPS-Committee has reviewed this and made a decisionIssue-Enhancementthe issue is more of a feature request than a bugIssue-Questionideally support can be provided via other mechanisms, but sometimes folks do open an issue to get aKeepOpenThe bot will ignore these and not auto-closeUp-for-GrabsUp-for-grabs issues are not high priorities, and may be opportunities for external contributorsWG-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