gpt4 book ai didi

sql - .NET SqlConnection.Dispose() 可以抛出异常吗?

转载 作者:行者123 更新时间:2023-12-02 08:30:26 24 4
gpt4 key购买 nike

SqlConnnection 对象的Dispose 方法是否可能抛出异常?它总是显示在 try-catch 之外的 finally block 中。如果 using block 等同于 try...finally 然后调用 Dispose,那么当 Dispose 抛出异常时似乎也是这种情况 会有问题。

最佳答案

技术上可以,但不应该:

CA1065: Do not raise exceptions in unexpected locations :

A IDisposable.Dispose method should not throw an exception. Dispose is often called as part of the clean up logic in a finally clause. Therefore, explicitly throwing an exception from Dispose forces the user to add exception handling inside the finally clause. The Dispose(false) code path should never throw exceptions, because this is almost always called from a finalizer.

Dispose Dos and Don'ts :

Don't throw exceptions in Dispose. Nothing should go wrong with your object calling Dispose.

这个故事的寓意似乎是从 Dispose 抛出的异常是一件非常糟糕的事情(出于您提到的某些原因)并且应该尽可能高地处理(没有什么你可以解决它,并且可能无法从中恢复)。

关于sql - .NET SqlConnection.Dispose() 可以抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27489042/

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