How can I rethrow an exception from catch block in PowerShell?

29,827

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.

Share:
29,827
vel
Author by

vel

Updated on July 05, 2022

Comments

  • vel
    vel almost 2 years

    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?

  • brianary
    brianary over 10 years
    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.
  • D.R.
    D.R. about 3 years
    It looks like it does nowadays!
  • aggieNick02
    aggieNick02 about 3 years
    Oh wow. I wonder when they changed it. It definitely didn't in 2017, when I had this related question: stackoverflow.com/questions/46162493
  • aggieNick02
    aggieNick02 about 3 years
    @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.