82

Should I approach the exception handling in the same manner as .NET?

Then, how can I re-throw an exception from catch block in PowerShell?

Is throw is enough? Or would throw $_ be better?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
pencilCake
  • 51,323
  • 85
  • 226
  • 363

1 Answers1

137

If you would like to re-throw original exception you could use throw (most common), or throw $_, or throw $_.Exception

ps: inside catch variable $_ is not exception by itself, but System.Management.Automation.ErrorRecord that contains Exception


Note

The throw keyword at PowerShell behaves differently then .NET implementation: in .NET you can only throw System.Exceptions itself or its successors, but in PowerShell, you can throw anything and that is automatically wrapped up into a System.Management.Automation.RuntimeException. See snippet here.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Akim
  • 8,469
  • 2
  • 31
  • 49
  • 33
    Note: In C#, the `throw` form keeps the original exception's context (source location), but unfortunately this does not appear to be the case in PowerShell. – brianary Nov 14 '13 at 18:05
  • 3
    It looks like it does nowadays! – D.R. Mar 11 '21 at 11:24
  • 2
    Oh wow. I wonder when they changed it. It definitely didn't in 2017, when I had this related question: https://stackoverflow.com/questions/46162493 – aggieNick02 May 12 '21 at 14:45
  • 1
    @D.R. - any clue when they fixed it, or link to an issue about it that got resolved. Just curious, I'm looking a bit myself but haven't found it yet. – aggieNick02 May 12 '21 at 15:17