- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
与 c# 不同,VB.NET 具有在 Try/Catch/Finally 块中有条件地捕获异常的功能。
我想我在某处读到,这通常是不好的做法,因为它鼓励人们将(业务)逻辑放在异常处理机制中,而您最终会得到一个美化的 GoTo
.
Try
// Do something
Catch ex As MyException When [condition]
//
End Try
When
的合法案例?功能还是应该远离它?
最佳答案
我能想到的通常情况是当您只想根据该异常的内容捕获特定异常时。例如。:
Try
// Do something
Catch ex As SqlException When ex.Number = 547
// Constraint Violation
End Try
SqlException
s,然后检查
Number
属性,然后如果不匹配则必须重新抛出异常。
For instance, if you have a fairly general exception, like COMException, you typically only want to catch that when it represents a certain HRESULT. For instance, you want to let it go unhanded when it represents E_FAIL, but you want to catch it when it represents E_ACCESSDEINED because you have an alternative for that case. Here, this is a perfectly reasonable conditional catch clause:
Catch ex As System.Runtime.InteropServices.COMException When ex.ErrorCode() = &H80070005
The alternative is to place the condition within the catch block, and rethrow the exception if it doesn’t meet your criteria. For instance:
Catch ex As System.Runtime.InteropServices.COMException
If (ex.ErrorCode != &H80070005) Then Throw
Logically, this “catch/rethrow” pattern does the same thing as the filter did, but there is a subtle and important difference. If the exception goes unhandled, then the program state is quite different between the two. In the catch/rethrow case, the unhandled exception will appear to come from the Throw statement within the catch block. There will be no call stack beyond that, and any finally blocks up to the catch clause will have been executed. Both make debugging more difficult. In the filter case, the exception goes unhandled from the point of the original throw, and no program state has been changed by finally clauses.
关于VB.NET Try/Catch/When - 远离它还是有它的用处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19400579/
我是一名优秀的程序员,十分优秀!