Java异常02:捕获和抛出异常

时间:2021-09-09 22:12:33   收藏:0   阅读:61

捕获异常(try...catch...finally)

public class Hello {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //try...catch...finally关键字捕获异常,快捷键ctrl + alt + T
        try {
            System.out.println(a / b);
        } catch (Exception e) {  //指定要捕获的异常类型,默认是Exception
            System.out.println("这是Exception");
        } catch (Error e){
            System.out.println("这是Error");
        } catch (Throwable e) {  //catch代码块可以嵌套,最多只会执行一个。异常的范围顺序应由小到大
            System.out.println("这是Throwable");
        }
        finally {
            //finally代码块如果写了一定会执行,处理IO、资源等善后工作,如执行scanner.close(),可选
            System.out.println("finally代码块一定会执行");
        }
    }
}

抛出异常(throw,throws)

public class Hello {
    public static void main(String[] args) {
        new Hello().test(1, 0);
    }

    //假设方法内处理不了异常,就在方法外抛出这个异常
    public void test(int a, int b) throws ArithmeticException{  //throws关键字,方法外抛出异常
        if (b == 0){
            throw new ArithmeticException();  //throw关键字,方法内抛出异常
        }
        System.out.println(a / b);
    }
}

自定义异常

步骤

public class Hello {
    public static void main(String[] args) {
        //对于抛出了异常的方法,调用时一定要捕获
        try {
            test(11);  
        } catch (MyException e) {
            System.out.println("MyException=>" + e);  //e代表的就是toString()方法的内容
        }
    }

    //对于可能会存在异常的方法,主动抛出异常
    static void test(int a) throws MyException {  //方法外抛出自定义异常
        System.out.println("传递的参数为:" + a);
        if (a > 10){
            throw new MyException(a);  //方法内抛出自定义异常
        }
        System.out.println("OK");  //正常结束
    }
}

//自定义异常类,要继承其他异常类
class MyException extends Exception{
    //自定义异常的规则:如果数字大于10
    private int detail;
    public MyException(int a){
        detail = a;
    }

    //重写toString()方法:打印异常的信息
    @Override
    public String toString() {
        return "MyException{" + detail + ‘}‘;
    }
}

经验总结

原文:https://www.cnblogs.com/taoyuann/p/15242440.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!