创建并抛出新的异常

use*_*182 121 powershell

我如何在PowerShell中创建并抛出新的异常?

我想针对特定错误做不同的事情.

Wii*_*opp 184

要调用特定异常(如FileNotFoundException),请使用此格式

if (-not (Test-Path $file)) 
{
    throw [System.IO.FileNotFoundException] "$file not found."
}
Run Code Online (Sandbox Code Playgroud)

要抛出一般异常,请使用throw命令后跟一个字符串.

throw "Error trying to do a task"
Run Code Online (Sandbox Code Playgroud)

在catch中使用时,您可以提供有关触发错误的内容的其他信息

  • 如果您在脚本中使用 try..catches 并且您有多个调用特定异常的 catch 语句,那么您当然需要指定异常类型。我不确定为什么要引用 C++。在 Powershell 脚本中,throw 语句通常用于通过描述性消息退出脚本。我不想引发争论,但 Powershell 和 C++ 是截然不同的动物。应缓和将 C++ 或 C# 最佳实践应用于 Powershell,因为脚本与函数式编程更密切相关。 (4认同)

Dav*_*e F 12

您可以通过扩展 Exception 类来引发自己的自定义错误。

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
Run Code Online (Sandbox Code Playgroud)