推荐使用异常:
因为异常设计就是为了决解:
什么出了错?
在哪出的错?
为什么出错?
1.通过使用异常可以明确 错误的类型,错误的原因,错误出现的地方并且调用者强制处理,这提高程序的健壮性(robust)。而返回值方式需要调用者主动去处理。
2.使用异常可以使代码更加优雅/可读性提高。不用写各种if/else判断情况,只要发生了异常则直接终止程序的执行。
例子:
public class MainAction { @Autowired MyService myService; public void doTest() { String msg = null; if (myService.operationA()) { if (myService.operationB()) { if (myService.operationC()) { myService.operationD(); } else { msg = "operationC failed"; } } else { msg = "operationB failed"; } } else { msg = "operationA failed"; } if (msg != null) { tip(msg);// 提示用户操作失败 } } public void tip(String msg) { } } 作者:HowToPlay 链接:https://www.zhihu.com/question/28254987/answer/40192291 来源:知乎 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
使用异常的方式:
public class MainAction { @Autowired MyService myService; public void doTest() { try { if (!myService.operationA()) { throw new OperationFailedException("operationA failed"); } if (!myService.operationB()) { throw new OperationFailedException("operationB failed"); } if (!myService.operationC()) { throw new OperationFailedException("operationC failed"); } myService.operationD(); } catch (OperationFailedException e) { tip(e.getMessage()); } catch(Exception e){ tip("error"); } } private class OperationFailedException extends Exception { public OperationFailedException(String message) { super(message); } } public void tip(String msg) { } } 或者在sevice层的操作中直接抛出异常,则可以改写为
try{
myService.operationA
myService.operationB
myService.operationC
myService.operationD
}catch(Exception e){
......
}