如何手动抛出异常--throw、throws了解一下

一.thorw的使用

  • 在日常的开发中,我们往往会使用到手动抛出异常,这里就需要用到thorw关键字
  • 代码示例:
/**
 * @ Author: Zhangyu
 * @ Date: 2020/7/27
 * @ Description:
 */
public class Test {
    public static void main(String[] args) {
        int num=1;
        try {
            if (num==1){
                throw new Exception();//手动抛出异常代码格式
            }
            System.out.println(num);

        }catch (Exception e) {
            System.out.println("已接住手动抛出异常");
        }
    }
}

输出结果:
已接住手动抛出异常

二.thorws异常

  • thorws的作用是将方法或类内遇到的指定异常抛出,由上一级处理
/**
 * @ Author: Zhangyu
 * @ Date: 2020/7/27
 * @ Description:
 */
public class Test {
    public  static void test()throws Exception{//将异常抛出方法,由上一级处理
        throw new Exception();
    }
    public static void main(String[] args) {

        try {
            test();//处理异常
        }catch (Exception e){
            System.out.println("已接收方法抛出的异常!");
        }
    }
}

输出结果:
已接收方法抛出的异常!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值