Java异常

java 异常

  • 检查类异常:用户错误或问题引起的异常,例如打开一个不存在的文件时,一个异常就发生了,这些异常在编译时不能被简单地忽略。
  • 运行时异常:运行时异常是可能被程序员避免的异常。与检查性异常相反,运行时异常可以在编译时被忽略。
  • 错误:错误不是异常,而是脱离程序员控制的问题。错误在代码中通常被忽略。例如,当栈溢出时,一个错误就发生了,他们在编译时也检查不到。
public class Demon01 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {  //try 监视区域
            System.out.println(a/b);
        }catch (ArithmeticException e){  //catch(想要捕获的异常类型)捕获异常
            System.out.println("错误");
        }finally {//处理善后工作
            System.out.println("finally");
        }
    }

finally可以不要

catch也可以捕获多个异常

    public static void main(String[] args) {
        int a=1;
        int b=0;
        try {  //try 监视区域
            System.out.println(a/b);
        }catch (ArithmeticException e){  //catch捕获异常
            System.out.println("错误");
        }catch (Error e){
            
        }finally {//处理善后工作
            System.out.println("finally");
        }
    }

大的异常写在后面,只会执行一个异常

快捷键:Ctrl+Alt+D

主动抛出异常:一般在方法中使用

    public static void main(String[] args) {
        Demon01 demon01 = new Demon01();
        demon01.test(1,0);
    }
    public void test(int a,int b){
        if(b==0){
            throw new ArithmeticException();
        }else{
            System.out.println(a/b);
        }
    }

方法上抛出异常

    public static void main(String[] args) {
       try {
           new Demon01().test(1,0);
       }catch (ArithmeticException e){
            e.printStackTrace();
       }
    }
    public void test(int a,int b) throws ArithmeticException{
        if(b==0){
            throw new ArithmeticException();
        }else{
            System.out.println(a/b);
        }
    }

结果如下:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值