轻松看透try、catch、finally

轻松看透try、catch、finally

//1、2说明只要try有异常,一定会执行catch,如果finally有返回,一定从finally返回
//3说明只要try没有异常,一定不执行catch
//4说明只要try没有异常,在try里返回数据且finally处没有返回,则finally没有改变try返回的数据
//5说明只要try没有异常,在try里不返回数据且finally处没有返回,则finally改变了try里面的数据

package com.app;

public class TryCatchFinally {

    @SuppressWarnings("finally")
    public static final String test1() {
        String t = "";

        try {
            t = t+"try";
            Integer.parseInt(null);
            return t;
        } catch (Exception e) {
            t = t+" catch";
            Integer.parseInt(null);
            return t;
        } finally {
            t = t+" finally";
            return t;
        }
    }
    @SuppressWarnings("finally")
    public static final String test2() {
        String t = "";

        try {
            t = t+"try";
            Integer.parseInt(null);
            return t;
        } catch (Exception e) {
            t = t+" catch";
            return t;
        } finally {
            t = t+" finally";
            return t;
        }
    }
    @SuppressWarnings("finally")
    public static final String test3() {
        String t = "";

        try {
            t = t+"try";
            return t;
        } catch (Exception e) {
            t = t+" catch";
            return t;
        } finally {
            t = t+" finally";
            return t;
        }
    }    @SuppressWarnings("finally")
    public static final String test4() {
        String t = "";

        try {
            t = t+"try";
            return t;
        } catch (Exception e) {
            t = t+" catch";
            return t;
        } finally {
            t = t+" finally";
        }
    }
    public static final String test5() {
        String t = "";

        try {
            t = t+"try";
        } catch (Exception e) {
            t = t+" catch";
            return t;
        } finally {
            t = t+" finally";
        }
        return t;
    }

    public static void main(String[] args) {
        //System.out.println(TryCatchFinally.test());
        System.out.println(TryCatchFinally.test1());
        System.out.println(TryCatchFinally.test2());//1、2说明只要try有异常,一定会执行catch,如果finally有返回,一定从finally返回
        System.out.println(TryCatchFinally.test3());//3说明只要try没有异常,一定不执行catch
        System.out.println(TryCatchFinally.test4());//4说明只要try没有异常,在try里返回数据且finally处没有返回,则finally没有改变try返回的数据
        System.out.println(TryCatchFinally.test5());//5说明只要try没有异常,在try里不返回数据且finally处没有返回,则finally改变了try里面的数据
    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值