小白学Java,用throws解决异常

小白学Java,用throws解决异常

package Example24;
/*

  • 用throws解决异常:
  • 1.定义方法时用throws直接抛出
  • public static int divide(int x,int y) throws Exception{
    int result =x/y;
    return result;
    }
  • 2.主方法中处理异常
  • public static void main(String[] args) {
    try {
    int result=divide(4,2);
    System.out.println(result);
    }catch(Exception e){
    System.out.println(“捕获的异常的类型:”+e.getMessage());
    e.printStackTrace();//打印捕捉的异常信息
    }
    finally {
    System.out.println(“进入finally代码块”);
    }
    }
    • 3.特别注意:当用throws抛出异常时,如果有错误程序会中止运行
  • */
    public class Example24 {
    public static void main(String[] args) {
    try {
    int result=divide(4,2);
    System.out.println(result);
    }catch(Exception e){
    System.out.println(“捕获的异常的类型:”+e.getMessage());
    e.printStackTrace();//打印捕捉的异常信息
    }
    finally {
    System.out.println(“进入finally代码块”);
    }
    }
    public static int divide(int x,int y) throws Exception{
    int result =x/y;
    return result;
    }
    }
    divide(4,2)给定数字正常代码运行结果:
    2
    进入finally代码块

divide(4,0)给定数字异常代码运行结果:
捕获的异常的类型:/ by zero
java.lang.ArithmeticException: / by zero
at Example24.Example24.divide(Example24.java:38)
at Example24.Example24.main(Example24.java:27)
进入finally代码块

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值