【问题标题】:Creating and throwing new exception创建并抛出新异常
【发布时间】:2012-08-16 05:34:11
【问题描述】:

如何在 PowerShell 中创建和引发新异常?

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

【问题讨论】:

标签: powershell


【解决方案1】:

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

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

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

throw "Error trying to do a task"

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

【讨论】:

  • 在 C++ 中,不鼓励抛出字符串,因为它们不在异常层次结构中。它只是工作,就像在 Powershell 中一样,但也许它们不是最好的方法?
  • 如果您在脚本中使用 try..catches 并且有多个调用特定异常的 catch 语句,那么您当然需要指定异常类型。我不确定为什么要引用 C++。在 Powershell 脚本中,throw 语句通常用于以描述性消息退出脚本。我不想引发争论,但 Powershell 和 C++ 是截然不同的动物。将 C++ 或 C# 最佳实践应用于 Powershell 应有所节制,因为脚本与函数式编程的联系更为密切。
【解决方案2】:

您可以通过扩展 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')
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 2016-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2014-10-28
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多