1

in powershell, under certain condition , i do this :

throw [System.Management.Automation.MethodException]

later i have catch like this :

catch [System.Management.Automation.MethodException]
{

catch
{

My code falls into the second (general) catch. when i look at $_.Exception in the second catch, it says 'System.Management.Automation.MethodException' - so why come Powershell does not catch it in the first catch ? How can i fix this?

Thanks, Peter

petercli
  • 629
  • 1
  • 8
  • 27
  • 1
    `throw [System.Management.Automation.MethodException]` -> `throw [System.Management.Automation.MethodException]::new()` – user4003407 Aug 26 '16 at 21:34

1 Answers1

1

PetSerAl has it right in the comment; you need to create an instance of the MethodException class.

His suggestion is nice and terse:

throw [System.Management.Automation.MethodException]::new()

But it only works on PowerShell 5+. In earlier versions:

$ex = New-Object -TypeName System.Management.Automation.MethodException
throw $ex

Or, an easy way to use this in any version while including a message is to cast a [String] as the exception:

throw [System.Management.Automation.MethodException]"You messed up."
briantist
  • 45,546
  • 6
  • 82
  • 127