异常或错误代码约定 [英] Conventions for exceptions or error codes

查看:60
本文介绍了异常或错误代码约定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天,我与同事就什么是首选的错误报告方法进行了激烈的辩论.主要是我们在讨论使用异常或错误代码来报告应用程序层或模块之间的错误.

Yesterday I was having a heated debate with a coworker on what would be the preferred error reporting method. Mainly we were discussing the usage of exceptions or error codes for reporting errors between application layers or modules.

您使用什么规则来决定是否抛出异常或返回错误代码以进行错误报告?

推荐答案

我通常更喜欢异常,因为它们具有更多的上下文信息,并且可以(如果正确使用)将错误更清楚地传达给程序员.

I normally prefer exceptions, because they have more contextual information and can convey (when properly used) the error to the programmer in a clearer fashion.

另一方面,错误代码比异常轻巧,但难以维护.错误检查可能会被无意中省略.错误代码更难维护,因为您必须保留所有错误代码的目录,然后打开结果以查看抛出了什么错误.错误范围在这里可能会有所帮助,因为如果我们唯一感兴趣的是是否存在错误,则检查起来更简单(例如,大于或等于0的HRESULT错误代码表示成功,小于零就是失败).可以无意中省略它们,因为没有程序性的强迫开发人员检查错误代码.另一方面,您不能忽略异常.

On the other hand, error codes are more lightweight than exceptions but are harder to maintain. Error checking can inadvertently be omitted. Error codes are harder to maintain because you have to keep a catalog with all error codes and then switch on the result to see what error was thrown. Error ranges can be of help here, because if the only thing we are interested in is if we are in the presence of an error or not, it is simpler to check (e.g., an HRESULT error code greater or equal to 0 is success and less than zero is failure). They can inadvertently be omitted because there is no programmatic forcing that the developer will check for error codes. On the other hand, you cannot ignore exceptions.

总而言之,在几乎所有情况下,我都倾向于使用异常而不是错误代码.

To summarize I prefer exceptions over error codes in almost all situations.

这篇关于异常或错误代码约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆