gpt4 book ai didi

c# - 我应该扔/期望扔什么?

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:45 25 4
gpt4 key购买 nike

我已经完全厌倦了我一直在编写的所有错误代码,所以看起来我真的需要了解处理异常的正确方法。

让我们考虑以下示例:

interface IDataSource
{
string ReadData(int offset);
}

class FileDataSource : IDataSource {...}
class DatabaseDataSource : IDataSource {...}

如果我正在使用实现 IDataSource 的类的对象,如果 ReadData() 由于某种原因失败,我可以期望捕获哪些异常?

FileDataSource 可能会失败,因为没有文件,或者文件小于偏移量。 DatabaseDataSource 可能会失败,因为它无法连接到数据库,或者该数据库中没有所需的表。

当我这样做时:
var data = dataSource.ReadData(10);

我应该捕获什么?另一方面,如果我正在实现一个新类 FakeDataSource ,如果发生不好的事情我应该扔什么?

我有一种感觉,当我抛出 FileNotFoundException来自 FileDataSourceSqlException来自 DatabaseDataSource这意味着违反封装,因为我知道实现细节。

是否应该由任何 IDataSource 引发的所有异常绑定(bind)到这个接口(interface)?我的意思是——当我定义任何新的抽象时,我是否也应该定义相关的异常?像这样:
interface IDataSource { ... }    
abstract class DataSourceException : Exception { ... }

所以,当有人决定实现 IDataSource ,他应该只扔 DataSourceException s。那是对的吗? offset 的错误值怎么办? - 我还应该扔 DataSourceException s 或标准 (.NET) ArgumentOutOfRangeException好吗?

还将感谢您认为值得的有关错误处理的文章的任何链接。

最佳答案

您应该只捕获您可以处理的异常。如果您的 IDataSource 抛出 FileNotFoundException 或 SqlException 并且您无法处理它,请不要捕获它。

抛出异常时,您应该抛出最能描述问题的异常类型。有three things that you want to know from a thrown exception .

  • What went wrong?
  • Where did it go wrong?
  • Why did it go wrong?

When exceptions are used effectively, what is answered by the type of exception thrown, where is answered by the exception stack trace, and why is answered by the exception message. If you find your exceptions aren't answering all three questions, chances are they aren't being used effectively. Three rules will help you make the best use of exceptions when debugging your programs. These rules are: be specific, throw early, and catch late.



在大多数情况下,使用通常定义的异常而不是创建自己的异常。人们将熟悉它们并理解它们的含义而无需额外解释。但是,在需要封装特定模块的详细信息的情况下,创建自己的异常类型可能会有所帮助。采用这种方法时,请将原始异常包装在模块的异常中,以便在重新抛出时不会丢失信息。

关于c# - 我应该扔/期望扔什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6802277/

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