I'm trying to create/throw own System.Exceptions in Powershell or .Net and catch those custom Exceptions, to handle the thrown Exception in an extended try-catch method.
The Example below is just to Show what I actually want to accomplish. I do know, that It could be handled differently with case or if-else Statements.
Is there any way to do so?
I've looked into:
- Creating own Classes (Too inconvenient)
- Write-Error ... -ErrorAction Stop (Couldn't figure it out)
- Creating new Error-Instances of the same Error (Couldn't figure out how to catch the Instance)
- Trying to use $PSItem to catch the previous Error and throw it again, modified (multiple Catches with the Same Error-Handle or Catches with Error-Handle and Parameters didn't work when I tried)
Thank you very much!
Example Powershell Script:
$j = 1
try{
$i = 1+1
if(i -eq 2){
# Throw custom Exception [ERR_eq_2]: "ERR- $i equals 2"
}else{
# Throw custom Exception [ERR_gt_3]: "ERR- $i doesn't equal 2"
}
}catch [ERR_eq_2]{
$i = $i + $j
$i--
if($i -gt 3){
# Throw custom Exception [ERR_gt_3]: "ERR- $i greater than 3"
}else{
# Do smth then continue
}
}catch [ERR_gt_3]{
Write-Output 'Meow'
#... And so on It's Customized
}catch ...