83

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?

1 Answer 1

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.

4
  • 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, 2013 at 18:05
  • 3
    It looks like it does nowadays!
    – D.R.
    Mar 11, 2021 at 11:24
  • 2
    Oh wow. I wonder when they changed it. It definitely didn't in 2017, when I had this related question: stackoverflow.com/questions/46162493 May 12, 2021 at 14:45
  • 2
    @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. May 12, 2021 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.