Dav*_* Wu 3 powershell exception throw
如何在PowerShell中使用'throw'方向来抛出自定义数据对象的异常?说,它能做到吗?:
throw 'foo', $myData
Run Code Online (Sandbox Code Playgroud)
那么数据可以用在'catch'逻辑中:
catch {
if ($_.exception.some_property -eq 'foo') {
$data = $_.exception.some_field_to_get_data
# dealing with data
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我的目的是知道是否有一个简短而酷的语法来抛出异常(没有显式创建我自己的类型),其名称我可以通过其名称来决定并在'catch'块中处理它的数据.
你可以使用throw任何类型的System.Exception实例(这里使用一个XamlException例子):
try {
$Exception = New-Object System.Xaml.XamlException -ArgumentList ("Bad XAML!", $null, 10, 2)
throw $Exception
}
catch{
if($_.Exception.LineNumber -eq 10){
Write-Host "Error on line 10, position $($_.Exception.LinePosition)"
}
}
Run Code Online (Sandbox Code Playgroud)
如果您运行的是5.0或更高版本的PowerShell,则可以使用新的PowerShell类功能来定义自定义异常类型:
class MyException : System.Exception
{
[string]$AnotherMessage
[int]$SomeNumber
MyException($Message,$AnotherMessage,$SomeNumber) : base($Message){
$this.AnotherMessage = $AnotherMessage
$this.SomeNumber = $SomeNumber
}
}
try{
throw [MyException]::new('Fail!','Something terrible happened',135)
}
catch [MyException] {
$e = $_.Exception
if($e.AnotherMessage -eq 'Something terrible happened'){
Write-Warning "$($e.SomeNumber) terrible things happened"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2966 次 |
| 最近记录: |