0
votes

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 ...
1

1 Answers

0
votes

The easiest way to do this would be to create a PS object of a known exception type. eg:

try
{
    $obj = New-Object System.AccessViolationException
    throw $obj
}
catch [System.AccessViolationException]
{
    "do stuff"
}

Here is a list of all .net exceptions. I don't know if it covers all. But all u gotta do is create it with New-object, then throw it as shwon and catch it wherever u want. You can pick any arbitrary exception and throw it.

The default throw of string would generate System.Management.Automation.RuntimeException

If you are looking to use an exception type that doesn't exist already I am not sure how to do it without creating a class.