Java:try与finally的说明

来源:互联网 发布:剑灵女帝捏脸数据 编辑:程序博客网 时间:2024/06/06 05:10

任何调用try 或者catch中的return语句之前,都会先执行finally语句,当然前提是finally存在。如果finally中有return语句,那么程序就return了,所以finally中的return是一定会被return的,编译器把finally中的return实现为一个warning。

例一

package exercise;/** * 基本类型测试try,finally * @author Administrator **/public class TestReturnAndFinally {    public static void main(String[] args) {    System.out.println(new TestReturnAndFinally().test());;    }    static int test() {        int x = 1;        try {            return x;        }        finally {            ++x;        }    }}结果: 1

解释:对于例一来说,一开始现在栈中存放了一个值为1的变量x,return x执行完了以后,x存到了寄存器中,接着执行++x,此时x的值为2,接着又执行return x,此时寄存器中的值被返回出去了,栈销毁。

例二

// 引用类型测试try,finallypublic class TestReturnAndFinally {    public static void main(String[] args) {        System.out.println(test());;    }    static StringBuffer test() {        StringBuffer x = new StringBuffer("X");        try {            x.append("W");            //打印x的地址值            //System.out.println(x.hashCode());            return x;        }        finally {           x.append("Y");           //System.out.println("Y "+x.hashCode());        }    }}结果: XWY

对于例二的解释:一开始StringBuffer里面有“X”接着a.append(“W”)就增加了”W”,紧接着return x,此时,将x存放在一个缓冲区当中,接着执行x.append(“Y”);此时缓冲区中就是X W Y,接着执行return a,输出缓冲区中的东西。用hashCode()方法可以打印对象地址。例二中的地址值是一样的。

例三

//普通类public class Quote {public int a = 1;}/** * 引用类型中的基本类型测试try,finally **/public class TestReturnAndFinally {    public static void main(String[] args) {        System.out.println(test());;    }    static String test() {        StringBuffer x = new StringBuffer("X");        try {   //System.out.println(x.hashCode());//356573597    //System.out.println(x.toString().hashCode());//88            return x.toString();        }        finally {           x.append("Y");        //System.out.println(x.hashCode());//356573597     //System.out.println(x.toString().hashCode());//2817        }    }}测试结果:X

请读者根据输出的地址值区仔细领悟x和x.toString.

finally代码块:定义一定执行的代码,通常用于关闭资源。
try…..catch一般有三种格式:

//第一个格式:try{}catch(){}//第二个格式:try{}catch(){}finally{}//第三个格式:try{}finally{}//记住一点:catch是用于处理异常。如果没有catch就代表异常没有被处理过。如果该异常是检测时异常。那么必须声明。
0 0
原创粉丝点击