java 异常之我见

1.异常类结构图:
这里写图片描述
2.异常链
未了提高代码的可理解性、系统的可维护性和友好性,我推荐使用异常链,以下是使用异常链的例子:
MyException.java

public class MyException extends Exception{
    public MyException () {}
    public MyException (String msg) {
        super(msg);
    }
}

Test.java

public class Test {
    public String display (int i) throws MyException{
        String returnMsg = "";
        if (i == 0) {
            throw new MyException("i的值不能为空!");
        } else {
            System.out.println("i/2");
        }
        try {
            Integer.parseInt("");
        } catch (Exception e) {
            throw new MyException("数值类型转换错误!" + e);
        } finally {
            System.out.println("我是finally,我一定会执行!");  // 猜猜这个会执行么?
        }
        System.out.println("我执行了啊~~~");
        return returnMsg;
    }
    public String display2 (int i) throws MyException{
        String returnMsg = "";
        try {
            display(i);
        } catch (MyException e) {
            throw new MyException(e.getMessage() + e);
        }
        return returnMsg;
    }
    public static void main (String[] args) {
        Test test = new Test();
        try {
            test.display2(0);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}

猜你喜欢

转载自blog.csdn.net/chen_jl168/article/details/79196576