【发布时间】:2012-08-16 05:34:11
【问题描述】:
如何在 PowerShell 中创建和引发新异常?
我想针对特定错误做不同的事情。
【问题讨论】:
-
您是否要抛出自定义异常? [this][1] 有帮助吗? [1]:stackoverflow.com/questions/11703180/…
标签: powershell
如何在 PowerShell 中创建和引发新异常?
我想针对特定错误做不同的事情。
【问题讨论】:
标签: powershell
要调用特定异常,例如 FileNotFoundException,请使用此格式
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
要抛出一般异常,请使用 throw 命令后跟一个字符串。
throw "Error trying to do a task"
在 catch 中使用时,您可以提供有关触发错误的其他信息
【讨论】:
您可以通过扩展 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')
}
【讨论】: