gpt4 book ai didi

VB.NET Try/Catch/When - 远离它还是有它的用处?

转载 作者:行者123 更新时间:2023-12-04 14:59:29 25 4
gpt4 key购买 nike

与 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属性,然后如果不匹配则必须重新抛出异常。

另见 The good and bad of exception filters :

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com