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.
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"
}
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With