如何在PowerShell中创建并抛出新的异常?
我想针对特定错误做不同的事情。
答案 0 :(得分:176)
要调用特定的异常,例如FileNotFoundException,请使用此格式
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
要抛出一般异常,请使用throw命令后跟一个字符串。
throw "Error trying to do a task"
在catch中使用时,您可以提供有关触发错误的内容的其他信息
答案 1 :(得分:1)
您可以通过扩展 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')
}