异常后被返回null被设计不好 [英] Is returning null after exception is caught bad design

查看:131
本文介绍了异常后被返回null被设计不好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是遇到同样的问题,当异常被捕获在一个非空返回值的函数中时,我不知道该返回什么。以下代码片段说明了我的问题。

  public Object getObject(){
try {
..
返回对象;
}
catch(异常e){
//我必须在这里返回一些什么?
返回null; //这是一个糟糕的设计?
}
}

所以我的问题是:




  • 返回空值不好设计?

  • 如果是这样清洁解决方案?



谢谢。

解决方案

我会说不要捕获异常,如果你真的不能处理它。并且记录不被视为处理错误。更好地把它吹到一个可以通过抛出异常的人。



如果你必须返回一个值,而null是唯一有意义的事情,那没有什么问题。只需记录它,并向用户清楚应该做什么。有一个单元测试显示抛出的异常,所以开发人员可以看到接受的成语需要什么。它也将测试,以确保您的代码抛出异常,当它应该。


I always come across the same problem that when an exception is caught in a function that has a non-void return value I don't know what to return. The following code snippet illustrates my problem.

public Object getObject(){
  try{
    ...
    return object;
  }
  catch(Exception e){
    //I have to return something here but what??
    return null; // is this a bad design??
  }
}

So my questions are:

  • Is return null bad design?
  • If so what is seen as a cleaner solution??

thanks.

解决方案

I would say don't catch the exception if you really can't handle it. And logging isn't considered handling an error. Better to bubble it up to someone who can by throwing the exception.

If you must return a value, and null is the only sensible thing, there's nothing wrong with that. Just document it and make it clear to users what ought to be done. Have a unit test that shows the exception being thrown so developers coming after you can see what the accepted idiom needs to be. It'll also test to make sure that your code throws the exception when it should.

这篇关于异常后被返回null被设计不好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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