java找不到对象提示,是否有标准的java异常类,意味着“找不到对象”?

Consider a function of the following general form:

Foo findFoo(Collection foos, otherarguments)

throws ObjectNotFoundException {

for(Foo foo : foos){

if(/* foo meets some condition*/){

return foo;

}

}

throw new ObjectNotFoundException();

}

A concrete case, for example, would be:

User findUserByName(Collection users, String name)

throws ObjectNotFoundException {

for(User user : users){

if(user.getName().equals(name)){

return user;

}

}

throw new ObjectNotFoundException();

}

These functions throw an exception if the object is not found. I can create a custom exception class for this purpose (in the examples, ObjectNotFoundException) but I would prefer to use an existing class. However, I could not find any exception class with this meaning in the standard java library. Do you know if there is a standard exception that can be used here?

解决方案

Do you know if there is a standard exception that can be used here?

There are a couple of exceptions that could be used (e.g. NoSuchElementException or IllegalArgumentException) but the answer really depends on the semantics that you intend to convey:

NoSuchElementException tends to be used when you are stepping through an sequence or enumeration, where what you have here is a lookup.

IllegalArgumentException tends to imply that the argument is in error, but in this case, it could be that the assumptions of the caller are incorrect, or something that is specific to the application logic.

A custom exception allows you to say (in the javadocs) exactly what the exception means. You can also declare it to be checked ... if that it appropriate.

(But don't be tempted to use UnknownUserException. That would be horribly wrong; read the javadoc!)

It is also worth considering returning null, especially if lookup failure is likely to be a fairly common (non-exceptional) event in your application. However, the downside of returning null is that the caller needs to check for null or risk unexpected NullPointerExceptions. Indeed, I would argue that over-use of null is worse than over-use of exceptions. The former can result in unreliable applications, whereas the latter is "only" bad for performance.

For Java 8 and onwards, returning an Optional would be a cleaner choice than returning a null.

In these things, it is important to look beyond the dogmas, and make up your mind based on what the actual context requires.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值