Abnormal supplements and custom exceptions

Custom exception

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)

Abnormal use experience

  • Reasonable use of logic to avoid exceptions, while assisting try catch processing (stable as an old dog)
  • When multiple catches are used, catch Exception is added at the end to prevent omission ( catch up and kill)
  • If you are not sure whether an abnormal code will be generated, use try catch (preferably kill the error rather than let it go)
  • Try to deal with exceptions, rather than dumping the pot to others. (Resolve your own affairs)
  • How to handle exceptions based on business needs and types of exceptions (according to local conditions)
  • Try to add finally block to release the occupied resources. (Can't occupy that pit without shit)

Guess you like

Origin www.cnblogs.com/li33/p/12713400.html