如何在 PowerShell 中从 catch 块重新抛出异常?

我是否应该采用与.NET 相同的方式处理异常?

然后,如何在 PowerShell 中从 catch 块重新抛出异常?

throw够吗? 还是 throw $_更好?

32979 次浏览

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.