异常捕获和抛出异常

异常处理机制:

  • 抛出异常

  • 捕获异常

  • 异常处理五个关键字

    • 1.try:监控区域

    • catch:捕获异常

    • finally:处理善后工作

    • throw:制造异常

    • throws:抛出异常

    try catch是遇到错误也能运行运行,throw 和 throws 是运行的时候给你抛出异常

//异常代码
package exception;
public class Text {
    public static void main(String[] args) {
        int a =1;
        int b =0;
        System.out.println(a/b);
    }
}
//输出:(报错:零不能被除)
//Exception in thread "main" java.lang.ArithmeticException: / by zero
//  at exception.Text.main(Text.java:8)


运用 try catch 捕捉异常,可以不要finally(在IO流以及一些资源中,关闭的方法都放在finally中)

//捕捉后  运行不报错
package exception;
​
public class Text {
    public static void main(String[] args) {
        int a =1;
        int b =0;
        //try catch是必须要的  finally可要可不要
        try {//try监控区域
            System.out.println(a/b);
        }catch (Error e){//cath(想要捕获的异常类型) 捕获异常
            System.out.println("程序出现异常,变量b不能为0");
        }finally {//finally 处理善后工作  程序出不出异常都会执行
            System.out.println("finally");
        }
​
    }
}
//输出:
//程序出现异常,变量b不能为0
//finally

快捷键:windo的是Ctrl+Alt+T Mac的是option+command+T

try {//try监控区域
            System.out.println();
        } catch (Exception e) {//cath 捕获异常
            e.printStackTrace();//自动生成  打印错误的栈信息
        } finally {
        }

主动抛出异常 throw 和 throws

throw:制造异常

public class Text {
    public static void main(String[] args) {
         new Text2().text(1,0);
    }
    public  void text(int a,int b){
        if (b == 0) {//throw
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}
//输出:Exception in thread "main" java.lang.ArithmeticException
//     at exception.Text2.text(Text2.java:11)
//     at exception.Text2.main(Text2.java:5)

throws:抛出异常

public class Text2 {
    public static void main(String[] args) {
        try {
            new Text2().text1(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
​
    }
//假设这方法中,处理不了这个异常,方法上抛出异常 抛到上一级
    public  void text1(int a,int b)throws ArithmeticException{
        if (b == 0) {//throw
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
    }
}
//输出:java.lang.ArithmeticException
//     at exception.Text2.text1(Text2.java:21)
//     at exception.Text2.main(Text2.java:6)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值