学习笔记---捕获和抛出异常

捕获和抛出异常

  • 抛出异常
  • 捕获异常

  • 关键词:try,catch,finally,throw,throws

  • 功能介绍
  1. try:监控区域
  2. catch:想要捕获的异常类型
  3. finally:处理善后工作,一定执行
  4. throw:多在方法内使用
  • 用法:
throw new ArithmeticException();	//ArithmeticException()可替换
  1. throws:在方法的声明定义处使用
  • 用法:
    public void test(int a, int b) throws ArithmeticException{}

  • try-catch-finally代码示例

  • 若要捕获多个异常,需从小到大

package Exception;

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

        //若要捕获多个异常,需从小到大
        try {   //try监控区域
            System.out.println(a/b);
        }catch(ArithmeticException e){  //想要捕获的异常类型
            System.out.println("除数b不能为0");
        }catch (Error e){
            System.out.println("Error");
        }catch (Exception e) {
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        } finally{   //处理善后工作
            System.out.println("善后工作,finally中的语句一定执行");
        }

        /*
        输出结果:
        除数b不能为0
        善后工作,finally中的语句一定执行
         */
    }
}


  • throw代码示例:
package Exception;

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

        new Demo02().test(a,b);
    }
    public void test(int a, int b){
        if(b==0){
            throw new ArithmeticException();
        }
        System.out.println("a/b");  //抛出后这里不执行
    }
}

  • throws代码示例:
package Exception;

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

        try {
            new Demo02().test(a,b);
        } catch (ArithmeticException e) {
            System.out.println("除数不能为0");
        } finally {
            System.out.println("善后区域");
        }
    }
    public void test(int a, int b) throws ArithmeticException{
        System.out.println(a/b);  //抛出后这里不执行
    }
    
    /*
    输出结果:
    除数不能为0
    善后区域
     */
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值