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中使用时,您可以提供有关触发错误的内容的其他信息
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)
| 归档时间: |
|
| 查看次数: |
129748 次 |
| 最近记录: |