JavaSE基础-异常

异常:程序中出现的一些错误,但并不是所有的错误都是异常。异常是可以预见,但不能修改的。

处理异常

try{}catch(ArithemticException e){}

public static void main(String[] args) {
    int a = 0;
    
    try {
        //非检查异常
        int b = a/0;
    } 
    //捕捉异常对象的名字
    catch (ArithmeticException e) {
        System.out.println("除数为0了,请检查代码,程序将终止运行");
        return;
    }
    finally{
            //在finally中写的代码,不论是否出现异常都会运行
            System.out.println("finally....");
        }
    
    System.out.println("aaaaa");

throw关键字

public static void main(String[] args) {
    int a = 5;

    while (a > 0) {
        //
        try {
            func(a);
        } catch (Exception e) {

        }
        a--;
    }
}

public static void func(int a) throws Exception// 声明方法抛出异常
{
    try {
        System.out.println(123 / 0);
    } catch (Exception e) {

        System.out.println("除数为0");

        throw e;// 异常处理不了,将异常抛出
    }
}

 

posted @ 2021-08-03 19:05  暮商  阅读(42)  评论(0)    收藏  举报