当引发异常或返回null? [英] When to raise an exception or return null?

查看:208
本文介绍了当引发异常或返回null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据访问层上有一些函数

I have a few functions on Data access layer

public Order RetrieveById(int id)
public List<Order> RetrieveByStatus(OrderStatus status)

现在我有点混淆异常提高。

Now i am bit confuse on exception raising.

在RetrieveById函数的情况下,小于1的id是无效的id,所以我想提出一个异常。我觉得返回null为不存在于数据库中的Id。

In case of RetrieveById function, id which is less than 1 is an invalid id therefore i feel like raising an exception. And i feel like returning null for the Id which doesn't exist in the database. Then it feels like i am over complicating.

在RetrieveByStatus的情况下,当数据库中没有该状态的数据时,我想返回一个空列表。

In case of RetrieveByStatus, i feel like returning a empty list when there is no data in the database for that status.

但我已经看到一些人提出异常时RetrieveById不能返回任何东西,但RetrieveByStatus不应该引发异常,当没有记录或应该吗?

However i have seen that some people raising an exception when RetrieveById cannot return anything but then RetrieveByStatus should not raise exception when there is no record or should it?

有人可以为我澄清这些概念吗?

Could anyone please clarify these concepts for me?

推荐答案

第一种情况下,我可能会去一个异常,并处理自己,而不是返回null。如果你的第一个方法被使用的方式,返回的对象被保存到一个Order引用。这是一个很高的机会 NullReferenceException 被抛出,当有人试图调用该对象的方法或属性。

In the first case i would possibly go for a exception and handle myself,instead of returning null.What if your first method is used in a way that the returned object is saved to a Order reference.There is a very high chance of NullReferenceException being thrown,when someone tries to call a method or property on that object.

对于第二种方法,我会去一些人已经建议的空列表。

For the second method i would go for a empty list as some have suggested.

这篇关于当引发异常或返回null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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