您的位置:首页 > 其它

错误处理的返回--异常还是返回值

2016-03-17 16:07 176 查看
推荐使用异常:

因为异常设计就是为了决解:

什么出了错?

在哪出的错?

为什么出错?

1.通过使用异常可以明确错误的类型,错误的原因,错误出现的地方并且调用者强制处理,这提高程序的健壮性(robust)。而返回值方式需要调用者主动去处理。

2.使用异常可以使代码更加优雅/可读性提高。不用写各种if/else判断情况,只要发生了异常则直接终止程序的执行。

例子:

publicclassMainAction{
@Autowired
MyServicemyService;

publicvoiddoTest(){
Stringmsg=null;

if(myService.operationA()){
if(myService.operationB()){
if(myService.operationC()){
myService.operationD();
}else{
msg="operationCfailed";
}
}else{
msg="operationBfailed";
}
}else{
msg="operationAfailed";
}
if(msg!=null){
tip(msg);//提示用户操作失败
}
}

publicvoidtip(Stringmsg){
}
}

作者:HowToPlay
链接:https://www.zhihu.com/question/28254987/answer/40192291
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


使用异常的方式:

publicclassMainAction{
@Autowired
MyServicemyService;

publicvoiddoTest(){
try{
if(!myService.operationA()){
thrownewOperationFailedException("operationAfailed");
}
if(!myService.operationB()){
thrownewOperationFailedException("operationBfailed");
}
if(!myService.operationC()){
thrownewOperationFailedException("operationCfailed");
}
myService.operationD();
}catch(OperationFailedExceptione){
tip(e.getMessage());
}catch(Exceptione){
tip("error");
}
}

privateclassOperationFailedExceptionextendsException{
publicOperationFailedException(Stringmessage){
super(message);
}
}

publicvoidtip(Stringmsg){
}
}

或者在sevice层的操作中直接抛出异常,则可以改写为
try{

myService.operationA

myService.operationB

myService.operationC

myService.operationD


}catch(Exceptione){
  ......
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: