- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我已经完全厌倦了我一直在编写的所有错误代码,所以看起来我真的需要了解处理异常的正确方法。
让我们考虑以下示例:
interface IDataSource
{
string ReadData(int offset);
}
class FileDataSource : IDataSource {...}
class DatabaseDataSource : IDataSource {...}
var data = dataSource.ReadData(10);
FakeDataSource
,如果发生不好的事情我应该扔什么?
FileNotFoundException
来自
FileDataSource
或
SqlException
来自
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/
我正在创建一个系统。我想知道的是,如果一个消息不受支持,它应该怎么做?我应该说不受支持的消息吗?我应该返回 0 还是 -1?或者我应该设置一个 errno (base->errno_)。有些消息我不关
这个问题在这里已经有了答案: 关闭 10 年前。 Possible Duplicate: incorrect stacktrace by rethrow 人们普遍认为,在 .NET 中,throw;
这是我第一次使用 Passport 。 当我尝试启动我的应用程序时,我不断收到此错误: passport.use(new LocalStrategy(Account.authenticate()));
假设我正在做一些在抛出异常时需要清理的事情。 比如我正在创建一个动态数组,我需要构造对象,但是它们的构造函数可能会抛出异常: size_t const n = 100; T *const p = st
我正在为一种非常简单的编程语言编写 BNF 语法,并使用 Flex 和 Bison 进行编译。 我只有 3 种变量和常量类型:实数、整数、字符串。 我的 .l 文件具有“ID”的 token 定义,如
我是一名优秀的程序员,十分优秀!