zoukankan      html  css  js  c++  java
  • 异常的补充和自定义异常

    自定义异常

    public class MyException extends ArithmeticException{
        private int detail;
    
        public MyException(int a){
            this.detail = a;
        }
    //打印异常的信息
        @Override
        public String toString() {
            return "MyException{" +
                    "detail=" + detail +
                    '}';
        }
    }
    public class Test {
        static void test(int a){
            System.out.println("传递的参数是:"+ a);
            if(a > 10){
                throw new MyException(a);
            }
            System.out.println("OK");
        }
        public static void main(String[] args) {
            try{
                test(99);
            }catch (MyException e){
                System.out.println("MyException ===》》》" +e);
                e.printStackTrace();//实际上也调用toString方法了
            }
        }
    }
    结果:
        传递的参数是:99
        MyException ===》》》MyException{detail=99}
        MyException{detail=99}
    	at InnerCLass.Test.test(Test.java:7)
    	at InnerCLass.Test.main(Test.java:13)
    

    异常使用的经验

    • 合理的使用逻辑去避免异常,同时辅助try catch处理(稳如老狗)
    • 多个catch使用的时候,最末尾加上catch Exception防止遗漏(赶尽杀绝)
    • 不确定是否会产生异常的代码,也用try catch(宁杀错,不放过)
    • 尽量去处理异常,而不是甩锅给别人。(自己的事情自己解决)
    • 如何处理异常时根据业务需求和异常类型决定的(因地制宜)
    • 尽量添加finally语句块去释放占有的资源。(不能占着茅坑不拉屎)
  • 相关阅读:
    jQuery小案例
    update-alternatives
    计算机网络备忘
    报文交换 (转自百度百科,方便以后复习)
    erlang supervisor simple_one_for_one实例
    erlang supervisor中启动普通的进程
    erlang四大behaviour之一gen_server(转载)
    用Doxygen+Graphviz生成函数调用流程图(转)
    selenium模块
    request模块
  • 原文地址:https://www.cnblogs.com/li33/p/12713400.html
Copyright © 2011-2022 走看看