异常的捕获和抛出

异常的捕获和抛出

try-catch必须要有

finally可以不要,假设有io,一般在这里关闭

若要捕获多个异常:catch应该从小到大排列

快捷键:选中这行代码ctrl+alt+T ,选择相应选项,则自动包裹该代码

方法里抛出用throw ,方法上抛出用throws。

以上关键词的具体用法在下方程序中清楚展示:

package exception.demon1;

public class demon1 {


    public static void main(String[] args) {
        int a = 9;
        int b = 0;

        try {//监控区域

            if(b==0){
                throw new ArithmeticException(); //抛出异常
            }

            System.out.println(a / b);


        } catch //捕获异常
        (ArithmeticException e) { //(想要捕获的异常类型 自定名)
            System.out.println("出错啦");
            //方法区
        } catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable e){
            System.out.println("Throwable");}
        finally { //处理善后工作 终究会被执行
            System.out.println("不管有没出错都输出这句话");
        }
        //最终输出: 出错啦
//         不管有没出错都输出这句话


        new demon1().div(10,0);        //调用除法方法

    }
    //假设这个方法中,处理不了这个异常。就在"方法上抛出异常"
    public int div(int a,int b) throws AbstractMethodError //"方法上抛出异常"
    {
        if(b==0){
            throw new ArithmeticException(); //主动抛出异常
                                             //即使没有除法方法体,只要b满足等于0这个条件,就抛出异常
                                             //一般用于方法中
        }

        int result = a/b;
        System.out.println(result);
        return result;

    }
}

使用了try-catch后,捕获到异常,程序能够继续运行,这是使用它的一个好处。

posted @ 2020-11-08 18:00  SshadowHeart  阅读(75)  评论(0)    收藏  举报