日期:2014-05-20  浏览次数:20827 次

J2SE关于几个特殊的异常情况的疑问!
研究简单异常的时候遇到了这样二个问题,各位帮忙分析,
第一题:
Java code

public int method(){
        try{
            File f = new File("");
            FileInputStream fi = new FileInputStream(f);
            return 1;
        }catch (Exception e) {
            // TODO: handle exception
            throw new Exception();
        }finally{
            System.out.println("1");
                            return 2;
        }
    }



这道题catch中抛出了异常,按照常理应该在catch里面继续try{}catch(){}捕获异常。否则就会出现编译错误。
而如果我在finally中写上retrun 那么编译就不会出错了。搞不清楚是什么原因。

第二题:
Java code

public class ExceptionTest {
    public static void main(String[] args) {
        try {
            method();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            System.out.println("finally main");
        }
        
    }
    public static void method() throws Exception {
        try{
            throw new Exception();
        }finally{
            System.out.println("finally method");
        }
    }

}




这道题按照我最初的想法,首先执行method抛出异常然后执行finally输出"finally method",由于该方法采取躲避异常方式,所以main方法抓到异常,打印异常信息,输出"finally main"。
结果应该为:
finally method
java.lang.Exception
at bg.ExceptionTest.method(ExceptionTest.java:28)
at bg.ExceptionTest.main(ExceptionTest.java:17)
finally main


但是实际情况却不是这样,实际的结果可能有很多种

其中一种:
finally method
finally main
java.lang.Exception
at bg.ExceptionTest.method(ExceptionTest.java:28)
at bg.ExceptionTest.main(ExceptionTest.java:17)

其中一种:

finally method
java.lang.Exception
at bg.ExceptionTest.method(ExceptionTest.java:28)
at bg.ExceptionTest.main(ExceptionTest.java:17)
finally main
其中一种:

java.lang.Exception
at bg.ExceptionTest.method(ExceptionTest.java:28)
at bg.ExceptionTest.main(ExceptionTest.java:17)
finally method
finally main

(我跑了断点居然和线程有关,网上也没搜到有用的结论)。
忘有知道结果的大牛给出相关解释,学习一下!



------解决方案--------------------
第一道跟 返回值 有关系,你试试void再理解下。

第二道不知道,结果无序的。
------解决方案--------------------
返回值有返回不线程就结束了,就不执行了,所以必须在要执行的finally语句后面带return