我有一种情况,我必须在我的 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
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在不编写 .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 …Run Code Online (Sandbox Code Playgroud)