异常02:捕获和抛出异常

学习重点:

  1. 抛出异常
  2. 捕获异常
  3. 异常处理五个关键字:try,catch,finally,throw,throws
  4. 重点:五个方法和作用,如何要捕获如何要抛出

单个Catch捕获:

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

        //使用多个catch捕获,最大的异常写在最下面,有个层层递进的关系,先小范围后大范围
        try{//try监控区域
            System.out.println(a/b);
        }catch(Error e){//捕获异常  catch(想要捕获的异常类型!){}
            System.out.println("程序出现异常,变量b不能为0");
        } finally{//处理善后工作
            System.out.println("finally");
        }
        //总结:finally可以不要finally,假设IO,资源要关闭,则关闭工作放在finally里面。

        System.out.println(a/b);
    }
}

finally

finally可以不要finally,假设IO,资源要关闭,则关闭工作放在finally里面。

多个catch捕获

public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //要捕获多个异常要从小到大

        try {//try监控区域
            if(b==0){//主动抛出异常 throw
                throw new ArithmeticException();//主动抛出异常
            }
            System.out.println(a / b);
        } catch (Error e) {//捕获异常  catch(想要捕获的异常类型!){}
            System.out.println("Error");
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Throwable e) {
            System.out.println("Throwable");
        } finally {//处理善后工作
            System.out.println("finally");
        }

异常由大到小的优先级

Throwable包含了Exception和Error.


主动抛出异常throw和方法上抛出异常throws

throw:在方法中抛出异常

public void test(int a,int b){
    if(b==0){//主动抛出异常 throw
        throw new ArithmeticException();//主动抛出异常
    }
    System.out.println(a / b);
}
throw new ArithmeticException();//主动抛出异常,一般在方法中

throws:在方法上抛出异常

//假设方法中,处理不了这个异常。方法上抛出异常用throws
public void test(int a,int b) throws ArithmeticException{
    if(b==0){//主动抛出异常 throw throws
        throw new ArithmeticException();//主动抛出异常,一般在方法中
    }
    //System.out.println(a / b);
}

快捷方式:Ctrl+Alt+T

  • 选中可能异常部分按下快捷方式,选择捕获的方式。
posted @   夜月明  阅读(88)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示