2016-08-04 38 views
0

当我执行该代码我得到了“终于”它是否像reThrowing相同的异常?

public class Tester { 
    static void method() throws Exception { 
     throw new Exception(); 
    } 

    public static void main(String... args) { 
     try { 
      method(); 
     } catch (Throwable th) { 
      try { 
       new Exception(); 
      } catch (Exception e) { 
       System.out.print("Exception"); 
      } finally { 
       System.out.print("finally"); 
      } 
     } 
    } 
} 

无法找出执行的流程!

+0

你在上面的代码中有什么困惑? –

+0

我没有混淆,而是我跳过'新的异常();'认为这个异常实际上是抛出。 @RamanSahasi –

+0

没有问题,混乱是编程的一部分。 :) –

回答

0

上面提到的输出编码为

finally 

如果你想知道为什么产量不

Exception finally 

那是因为在下面的代码行

try { 
     new Exception(); 
    } 

你只是宣布一个新的Exception对象,你不是真的在扔它。

,如果你想输出为Exception finally,那么你必须通过把throw new Exception();而不是new Exception();

然后,代码看起来像把那个对象:

public class HelloWorld{ 
    static void method() throws Exception{ throw new Exception(); } 

    public static void main(String... args){ 
     try{method();} 
     catch(Throwable th) 
     { 
      try{ throw new Exception(); } 
      catch(Exception e){System.out.print("Exception");} 
      finally{System.out.print("finally");}  
     } 
    } 
} 

输出

Exceptionfinally 
0

如果代码try中存在或不存在异常,则将执行finally块。