2013-03-07 97 views
0

我已經制定了一項計劃,其中return語句的情況下,無論是內部的try塊或catch塊finally塊來執行最後,但是當我寫system.exit內嘗試塊在這種情況下,finally塊不執行,但我仍然要執行,你可以請指教,我需要補充Runtime.getRuntime().addShutdownHook在這種情況下,我需要補充的是應該在任何情況下要執行的代碼,即使system.exit被稱爲。請指教,下面是我的課關於excuting終於在system.exit情況下阻止也加入shutdownhook

public class Hello { 
    public static void hello(){ 
     try{ 
      System.out.println("hi"); 
      System.exit(1); 
      // return; 

      }catch(RuntimeException e) 
      {  //return; 
     } 
     finally{ 
      System.out.println("finally is still executed at last"); 
     } 
    } 
    public static void main(String[] args){ 
     Hello.hello(); 
    } 
} 

回答

1

1)一般你需要關閉掛鉤,如果你想在這個具體的情況下退出

public static void main(String[] args) throws Exception { 
    Runtime.getRuntime().addShutdownHook(new Thread() { 
     @Override 
     public void run() { 
      System.out.println("bye"); 
     } 
    }); 
    hello(); 
} 

2)後執行一些代碼有沒有必要關閉掛鉤,只是從代碼

public static void hello() { 
    try{ 
     System.out.println("hi"); 
    } catch (RuntimeException e) { 
     // 
    } finally{ 
     System.out.println("finally is still executed at last"); 
    } 
} 
+0

非常感謝,作爲建議由你讓我的上述節目說我想通過關閉鉤子程序執行後打印簡單SOP聲明,可否請你在我上面的程序改變代碼顯示 – user2129402 2013-03-07 06:18:38

+0

OK,加窒息的鉤子的例子 – 2013-03-07 06:29:37

0

,當你調用System.exit(1)

移除離開它會退出程序,並且JVM會強制停止執行程序。

爲什麼你會使用System.exit(1)如果你想一些代碼來退出後執行

簡單YOUT try塊中施加一定的條件,退出try塊,從而導致在每種情況下finnaly塊