例外VS特殊的返回值 [英] Exceptions vs Special return values

查看:96
本文介绍了例外VS特殊的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪一个是在编程一个更好的做法?

Which one is a better practice in programming?

我说的不是完全的排他性。它更喜欢的事情:

I am not talking about complete exclusivity. It's more for things like:

列表< T> .Find ,你在哪里得到默认(T),而不是或你的价值, ValueNotFound 异常(例如)。

list<T>.Find, where you get default(T) or your value, instead of ValueNotFound exception (example).

列表&LT; T&GT;。.IndexOf ,你在哪里得到-1或正确的索引

list<T>.IndexOf, where you get -1 or the correct index.

推荐答案

那么,答案是它依赖。

在那里的项目是不是在列表中没有找到的情况下,抛出异常是一个可怕的做法,因为这是该项目可能不会出现在列表中完全可行的。

In the case of where an item is not found in a list, throwing an exception is a horrible practice, because it's completely feasible that the item might not be in the list.

现在,如果这是某种形式的专业列表,该项目应绝对在列表中找到,那么就应该抛出一个异常,因为你已经遇到过这种情况并不可行/合理的。

Now if this was a specialized list of some sort, and the item should absolutely be found in the list, then that should throw an exception, because you have encountered a situation which was not feasible/reasonable.

一般而言,对于像商业规则之类的,专门的错误codeS更好,因为你知道这些事情发生的可能性,并要应对这些可能性。例外情况是,你不希望的情况下,并不能继续code执行,如果他们发生。

Generally speaking, for things like business rules and the like, specialized error codes are better, because you are aware of the possibility of these things happening, and want to react to those possibilities. Exceptions are for the cases that you don't expect, and can't continue with code execution if they occur.

这篇关于例外VS特殊的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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