throwing more than one custom exception in powershell

Viewed 6504

I have a situation where i have to throw multiple custom exceptions in a try block in my powershell script something like below

try {
    if (!$condition1) {
        throw [MyCustomException1] "Error1"
    }
    if (!$condition2) {
        throw [MyCustomException2] "Error2"
    }
}catch [MyCustomException1] {
    #do some business logic
}catch [MyCustomException2] {
    #do some other business logic
}catch{
    #do something else
}

Is there a way to do it in powershell without writing the .net class MyCustomException1 and MyCustomException2. I don't have to store any info in the class but i just need a way to differentiate the exceptions. I could do as below but i just wondering if something cleaner.

try {
    if (!$condition1) {
        throw "Error1"
    }
    if (!$condition2) {
        throw "Error2"
    }
}catch {
    if($_.tostring() -eq "Error1"){
        Write-Host "first exception"
    }elseif($_.tostring() -eq "Error2"){
        Write-Host "Second exception"
    }else {
        Write-Host "third exception"
    }
}

Note: I have already checked below stack overflow questions: powershell-creating-a-custom-exception powershell-2-0-try-catch-how-to-access-the-exception powershell-creating-and-throwing-new-exception But it doesn't answer my question.

4 Answers

I was just trying to find something really basic for error treatment and I came up with this:

try {
    $a = 1
    if($a-eq1) { throw "OneException" }
    if($a-eq2) { throw "TwoException" }
} catch {
    switch ($error[0]){
        "OneException" { echo "one" }
        "TwoException" { echo "two" }
        default { echo $_.Exception }
    }
}

Not fancy, but functional :)

Related