开发库时的断言与异常
我正在开发一个库,以便在其他库或最终产品中进一步使用。假设用户以错误的方式使用该库 - 将不适当的值传递给公共函数,以错误的顺序调用函数等。
在这种情况下,我可能会抛出异常,但这些通常是为最终产品设计的,并且必须妥善处理,而这里我们有一个开发人员错误,他们没有正确阅读文档。另一方面,他或她是我的库的用户,因此断言可能是一种错误的方式(想象一下在您从未编写过的代码中触发的断言,并且希望它能够工作)。
到目前为止,我仅在私有内部函数和方法中使用断言,因此仅通知我有关库内部我的错误。如果库用户错误使用,我总是抛出一个带有错误描述的异常(以及如何避免它的建议)。
您认为这是正确的做法吗?如果没有,那么在开发库时您使用哪种经验法则来处理断言和异常?
I am developing a library for further usage in other libraries or final products. Let's say a user uses the library in a wrong way - passing an inappropriate value to a public function, calling functions in the wrong order etc.
In this case I might throw an exception, but these are usually designed for the final products and must be appropriately handled, while here we have a developer mistake who haven't read the documentation properly. On the other hand, he or she is the user of my library and thus assertion may be a wrong way to go (imagine an assertion that fired in the code that you have never written and expected just to work).
So far I have been using assertions only inside private internal functions and methods, thus notifying only me about my errors inside of the library. In the case of wrong usage by the library users I always throw an exception with an error description (and advice how to avoid it).
Do you think this is a right approach? If not, which rule of thumb are you using for assertions and exceptions when developing a library?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是正确的做法。断言可以在私有函数内部使用。如果客户端使用不正确的参数调用公共方法,则应抛出异常。错误的代码必须立即使程序崩溃,这是修复错误的最佳机会。
对于预期情况(未找到文件、设备无响应等)和调用者错误(例如不正确的参数值),最好使用不同的异常类型。客户端代码应该捕获预期的异常,而不处理意外的异常。当抛出意外异常时,客户端程序崩溃,程序员只需修复错误即可。
但是,如果您的库是为同一家公司的内部使用而编写的,则可以使用断言来处理公共方法调用错误(例如私有方法)。但这种方法必须受到严格限制,不应该用于外部客户。
Yes, this is right approach. Assertion is OK for internal use in a private functions. In the case client calls public method with incorrect parameters, exception should be thrown. Incorrect code must crash the program immediately, this is the best chance to fix the bug.
It is a good idea to have different exception types for expected situations (file not found, device not responding etc.) and caller bugs like incorrect parameter value. Client code should catch expected exceptions, leaving unexpected exceptions unhandled. When unexpected exception is thrown, client program crashes, and programmer just fixes the bug.
However, if your library is written for internal use in the same company, it is OK to handle public method call errors like private, with assertions. But this approach must be strongly restricted and should not be used for external clients.
断言在发布程序集中不起作用,异常是通知库用户出现问题的唯一方法
Assertions will not work in Release assemblies, Exceptions is the only way to signal user of library that something is wrong