java中的try-catch-finally异常捕获

package com.imooc.exception;
/**
 * @author ausu: try-catch-finally异常捕获
 *
 */
public class Trycatchtest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Trycatchtest trycatchtest = new Trycatchtest();
        trycatchtest.test();
    }
    /**
     * while循环的异常捕获
     */
    public void test(){
        int divider = 10;
        int result = 100;
        try {
            /**
             * try中包含了需要捕获异常的代码块,如果,成功捕获异常,则执行相应的catch块;否则,略过catch块。
             */
            while (divider > -1) {
               divider--;
               result = result +100/divider;
            }
            //关于以下语句的执行问题:
            //   如果,在此语句前成功捕获到异常,则将跳过以下语句并执行相应的catch块中的异常处理代码。
            System.out.println("未捕获异常则输出我。");
            
        }catch(ArithmeticException e){
            /**TODO: 多个catch的存在,必须遵行先catch子类,在父类
             * 如:catch(ArithmeticException e)之后再catch(Exception e).
             *因为,ArithmeticException 是 Exception的子类。
             **/
            //TODO:处理该算术异常(ArithmeticException)的代码块。
            //调用此方法,打印异常的具体信息
            System.out.println("捕获到了循环中的算术异常,如下:");
            e.printStackTrace();
        }
        catch (Exception e) {
            // TODO: handle exception
            System.out.println("捕获到了循环中的异常,如下:");
            e.printStackTrace();
        }finally{
            /**
             * 执行最后的finally块中语句。
             */
            System.out.println("不管有没有捕获异常,最后都执行我。");
        }
        //至此,整个try-catch异常捕获结束,不管有没有捕获异常,都会执行下面语句。
        System.out.println(result);
    }
}
/**
 * 总结:
 *    关于try-catch-finally的异常捕获,我们使用try块来包含可能出现“异常的代码块”。
 *    1.如果,此代码块没有异常,则执行try块中的代码、finally块中的代码及异常捕获过程之后的代码。如:System.out.println(result);
 *    2.如果,此代码有异常,则在try块中捕获到异常,并在异常处跳转至相应的catch块中并执行其中的“异常处理代码”;
 *      再执行finally块中的代码及异常捕获过程之后的代码。如:System.out.println(result);
 *      
 *    总之,在try中捕获异常后>>catch异常处理>>finally》正常代码。
 *        在try中未捕获异常>>finally>>正常代码。
 *        
 *    即,提供:为可能出现异常的代码,增加一个捕获并能作出异常处理的功能。
 */

注:此博文为日常的学习总结,如有不当之处,请见谅!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值