Return 'null' or throw exception

本文讨论了当方法未能找到预期对象时,应该返回空值还是抛出异常的问题。文章指出如果总是期望能找到值,则找不到时应抛出异常;若值可能缺失且这在应用逻辑中有效,则应返回空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://stackoverflow.com/questions/175532/return-null-or-throw-exception

 

I have a method that is suppose to return an object if it is found.

If it is not found, should I:

a) return null
b) throw an exception
c) other

if you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.

If the value can be missing or present and both are valid for the application logic then return a null.

More important: What do you do other places in the code? Consistency is important.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值