zoukankan      html  css  js  c++  java
  • 错误处理的返回--异常还是返回值

     推荐使用异常:

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

       什么出了错?

       在哪出的错?

       为什么出错?

     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){
      ......
    }
     
    
    
  • 相关阅读:
    如何解决selenium打开chrome提示chromedriver.exe已停止工作
    移动端弱网测试 fiddle
    android 真机设备识别不出adb interface
    网络基础知识
    《Mongo权威指南》学习手记
    MongoDB数据库备份
    windows下安装mongoDB(zip版)
    ubuntu apt
    docker 免sudo设置(仅3个命令)
    ubuntu18.04双卡机安装ubidia驱动遇到的坑
  • 原文地址:https://www.cnblogs.com/predisw/p/5287806.html
Copyright © 2011-2022 走看看