Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing more than one custom exception in powershell

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.

like image 768
Pramod Avatar asked Nov 16 '25 20:11

Pramod


2 Answers

Thanks @BenH and @TheIncorrigible1 for your pointers on creating classes and Exceptions. Below is a sample code to achieve this if some one else also looking for the same.

class MyEXCP1: System.Exception{
    $Emessage
    MyEXCP1([string]$msg){
        $this.Emessage=$msg
    }
}
class MyEXCP2: System.Exception{
    $Emessage
    MyEXCP2([string]$msg){
        $this.Emessage=$msg
    }
}
$var=2
try{
    if($var -eq 1){
        throw [MyEXCP1]"Exception 1"
    }
    if($var -eq 2){
        throw [MyEXCP2]"Exception 2"
    }
}catch [MyEXCP1]{
    Write-Output "Exception 1 thrown"
}catch [MyEXCP2]{
    Write-Output "Exception 2 thrown"
}
like image 89
Pramod Avatar answered Nov 18 '25 11:11

Pramod


You could look at the FullyQualifiedErrorID property on the $error variable to get the string from the throw statement.

try {throw "b"}
catch {
    if ($error[0].FullyQualifiedErrorID -eq "a") {'You found error "a"'}
    if ($error[0].FullyQualifiedErrorID -eq "b") {'You found error "b"'}
}

But it looks like you don't really want to Try Catch but to make non-terminating errors. You could use Write-Error to do this.

if (!$condition1) {
    Write-Error "Error1"
}
if (!$condition2) {
    Write-Error "Error2"
}
like image 28
BenH Avatar answered Nov 18 '25 11:11

BenH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!