73

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
  • 167,268
  • 50
  • 405
  • 846
pencilCake
  • 48,449
  • 79
  • 219
  • 356

1 Answers1

127

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
  • 167,268
  • 50
  • 405
  • 846
Akim
  • 8,209
  • 2
  • 30
  • 48
  • 32
    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
  • 1
    It looks like it does nowadays! – D.R. Mar 11 '21 at 11:24
  • 1
    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
  • @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