Search code examples
powershellexceptionthrow

Powershell throw exceptions with data


How to use 'throw' direction in PowerShell to throw an exception with custom data object? Say, could it do this?:

throw 'foo', $myData

then the data can be used in 'catch' logic:

catch {
    if ($_.exception.some_property -eq 'foo') {
        $data = $_.exception.some_field_to_get_data
        # dealing with data
    }
}

edited:
My intention is to know is there a brief and cool syntax to throw an exception (without explicitly creating my own type) with a name that I can decide by its name and deal with its data in the 'catch' blocks.


Solution

  • You can throw any kind of System.Exception instance (here using a XamlException as an example):

    try {
        $Exception = New-Object System.Xaml.XamlException -ArgumentList ("Bad XAML!", $null, 10, 2)
        throw $Exception
    }
    catch{
        if($_.Exception.LineNumber -eq 10){
            Write-Host "Error on line 10, position $($_.Exception.LinePosition)"
        }
    }
    

    If you're running version 5.0 or newer of PowerShell, you can use the new PowerShell Classes feature to define custom Exception types:

    class MyException : System.Exception
    {
        [string]$AnotherMessage
        [int]$SomeNumber
    
        MyException($Message,$AnotherMessage,$SomeNumber) : base($Message){
            $this.AnotherMessage = $AnotherMessage
            $this.SomeNumber     = $SomeNumber
        }
    }
    
    try{
        throw [MyException]::new('Fail!','Something terrible happened',135)
    }
    catch [MyException] {
        $e = $_.Exception
        if($e.AnotherMessage -eq 'Something terrible happened'){
            Write-Warning "$($e.SomeNumber) terrible things happened"
        }
    }