【发布时间】:2022-05-20 05:02:24
【问题描述】:
我有一种情况,我必须在我的 powershell 脚本的 try 块中抛出多个自定义异常,如下所示
try {
if (!$condition1) {
throw [MyCustomException1] "Error1"
}
if (!$condition2) {
throw [MyCustomException2] "Error2"
}
}catch [MyCustomException1] {
#do some business logic
}catch [MyCustomException2] {
#do some other business logic
}catch{
#do something else
}
有没有办法在powershell中做到这一点,而无需编写.net类MyCustomException1和MyCustomException2。我不必在课堂上存储任何信息,但我只需要一种方法来区分异常。
我可以这样做,但我只是想知道是否更清洁。
try {
if (!$condition1) {
throw "Error1"
}
if (!$condition2) {
throw "Error2"
}
}catch {
if($_.tostring() -eq "Error1"){
Write-Host "first exception"
}elseif($_.tostring() -eq "Error2"){
Write-Host "Second exception"
}else {
Write-Host "third exception"
}
}
注意:我已经检查了下面的堆栈溢出问题:powershell-creating-a-custom-exceptionpowershell-2-0-try-catch-how-to-access-the-exceptionpowershell-creating-and-throwing-new-exception 但它没有回答我的问题。
【问题讨论】:
标签: powershell exception-handling