您的位置:首页 > 其它

try catch finally问题

2016-11-19 15:09 190 查看
1. try catch finally 执行顺序问题

例如:

class Test {

    public static void main( String args[] ) {

        System.out.println( Test.test() );

    }

    public static String test() {

        try {

            System.out.println( "try" );

            throw new Exception();

        }

        catch ( Exception e ) {

            System.out.println( "catch" );

            return "return";

        }

        finally {

            System.out.println( "finally" );

        }

    }

}

执行结果是:

try

catch

finally

return

2. 即使try块中没有发生异常,也就是说catch块没有被执行,finally块也会被执行

例子:

class Test {

    public static void main( String args[] ) {

        System.out.println( Test.test() );

    }

    public static String test() {

        try {

            System.out.println( "try" );

        }

        catch ( Exception e ) {

            System.out.println( "catch" );

            return "return";

        }

        finally {

            System.out.println( "finally" );

            return "return in finally";

        }

    }

}

执行结果是:

try

finally

return in finally
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: