zoukankan      html  css  js  c++  java
  • 异常的捕获和抛出

    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;
    
    }
    

    }

  • 相关阅读:
    WPF项目学习.一
    AtCoder Beginner Contest 210 A~D 题解
    P7715 「EZEC-10」Shape 题解
    P6216 回文匹配 题解
    字符串学习笔记
    #2742. 「JOI Open 2016」销售基因链
    树状数组学习笔记
    2021 省选游记
    AtCoder Beginner Contest 196 E
    AtCoder Regular Contest 113 A~D题解
  • 原文地址:https://www.cnblogs.com/w2758472746/p/14021215.html
Copyright © 2011-2022 走看看