绕过java的try / catch并保持代码干净而不返回null [英] Get around java's try/catch and keep the code clean without returning a null
问题描述
我有这段代码:
private void myFunc(){
obj = doSomething();
//If value is found, doX()
//If value is not found, doY()
}
private obj doSomething(){
//Do some stuff
//Hit database to get some value
obj = db.getValue(); //This func throws an exception if no value is found
}
现在,我的问题是:
1.我应该这样做: doSomething()抛出ValueNotFoundException
并在myFunc()中捕获它:
2.或者在doSomething()中捕获它并返回null? (虽然这是一个非常糟糕的方法)。然后在myFunc中检查null()
Now, my question is:
1. Should I do: doSomething() throws ValueNotFoundException
and catch it in myFunc()
2. Or catch it in doSomething() and return null? (a very bad approach though). And then check for null in myFunc()
更新:
1.未找到的值是可能的而不是错误。
Update:
1. Value not found is something which is probable and not an error.
推荐答案
好吧,找不到值 例外(表示错误)或可能?如果 doSomething()
绝对不可能找不到它需要的东西,那就错了。我猜 myFunc()
不适合处理此类错误。
Well, is value not found something exceptional (indicating an error) or probable? If it is absolutely not possible that doSomething()
can't find what it needs, this is an error. I guess myFunc()
is not the right place to handle such error.
如果 doSomething()
有时找不到这个或那个(因为输入不正确,配置错误等)然后它应该不抛出异常并让客户端处理这个预期情况。但是 null
不是最佳返回值。相反,请考虑 null-object 设计模式或者像Scala中的 Option [T]
这样的包装器。
If doSomething()
sometimes can't find this or that (because the input is incorrect, misconfiguration, etc.) then it should not throw an exception and let the client handle this expected situation. However null
is not the best return value. Instead consider null-object design pattern or some wrapper like Option[T]
in Scala.
这是<$ c $的原因之一c> InputStream 不仅仅是抛出 EOFException 到达文件末尾时。这不是一个意外的情况。
This is one of the reasons why InputStream
is not simply throwing EOFException
when it reaches end of file. This is not an unexpected situation.
在Java中我尝试遵循一些技术/命名约定来使 null
更多显而易见:
In Java I try to follow some techniques/naming conventions to make null
more obvious:
private Obj tryReturningSomething()
private Obj returnSomethingOrNull()
此外,您始终可以使用JavaDoc来记录可能的返回值。我同意返回 null
不是最好的方法(例如,当方法返回一个集合时,我总是返回一个空的而不是 null
)但是在你的情况下,它仍然比抛出一个异常被抓住上面的一个堆栈帧。这是浪费的,难以维护和阅读。考虑有两个版本 - 一个返回 null
,一个抛出异常,包装第一个。
Also you can always use JavaDoc to document possible return value. I agree returning null
is not the best approach (e.g. when method returns a collection, I always return an empty one instead of null
) but in your case it is still better than throwing an exception to be caught one stack frame above. This is wasteful, harder to maintain and read. Consider having two version - one returning null
and one throwing an exception, wrapping the first one.
异常处理是发明了处理错误,而不是控制程序流程。
Exception handling was invented to handle errors, not to control the program flow.
这篇关于绕过java的try / catch并保持代码干净而不返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!