java 合理利用Exception

java异常抛出机制。先来看几组示例:

1、

public class Test{
    public static void main(String[] args){
        try {
            getAns();
        }catch (Exception e){
            System.out.println("123");
        }
    }
    public static void getAns() throws NullPointerException{
        try {
            Integer n = 0;
            Integer x = null;
            Integer y = x/n;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

结果:
在这里插入图片描述
说明是先走try()catch,如果没找到对应的,然后再走到throws。再来看一个例子

public class Test{
    public static void main(String[] args){
        try {
            getAns();
        }catch (NullPointerException e){
            System.out.println("123");
        }catch (Exception e){
            System.out.println("456");
        }
    }
    public static void getAns() throws NullPointerException{
        try {
            Integer n = 0;
            Integer x = null;
            Integer y = x/n;
        }catch (ArithmeticException e){
            e.printStackTrace();
        }
    }
}

结果是:
在这里插入图片描述
执行流程为:try catch,从上到下先找,如果再找throws。

2、局部异常化

public class Test{
    public static void main(String[] args){
        try {
            getAns();
        }catch (NullPointerException e){
            System.out.println("123");
        }catch (Exception e){
            System.out.println("456");
        }
    }
    public static void getAns() throws NullPointerException{
        Integer n = 0;
        Integer x = null;
        int k = x/n;
        try {
            Integer y = x/n;
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

在这里插入图片描述
局部异常catch和全局异常throws可以进行共存。如果需要全局异常throws,但是又不希望某些局部异常被throws了,所以try catch一定要细化,而不是写一个函数从整体上框住。

猜你喜欢

转载自blog.csdn.net/xielinrui123/article/details/88722329
今日推荐