java try 外面null,绕过java的try / catch并保持代码干净而不返回null

I have this piece of code:

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

}

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()

Update:

1. Value not found is something which is probable and not an error.

解决方案

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.

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.

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.

In Java I try to follow some techniques/naming conventions to make null more obvious:

private Obj tryReturningSomething()

private Obj returnSomethingOrNull()

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.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值