2016-05-12 84 views
1

我試圖重新執行的時間指定的方法號時異常的方法, 發生,但我無法重新執行方法如何調用指定的方法的時候發生異常

int maxretries=10; 
    void show(){ 
     try{ 
     display(); 
     } 
    catch(Exception e) 
    { 
    for(int i=1;i<maxretries;i++){ 
     display();//on first retry only I am getting exception 
    } 
    } 
    } 

當我運行的代碼,它是執行第一次重試,我收到異常,但我想重新執行display()方法,直到它在最大重試次數下成功執行。

+0

您是否考慮過調查爲什麼引發異常並修復潛在問題,而不是蠻橫地調用一個錯誤代碼並希望獲得最佳? – CptBartender

回答

2

您在catch中編寫的調用不在try中,因此它不會捕獲異常。

您需要使用其他概念來完成此操作,或者再次調用整個函數,或者編碼catch中的連續try塊(以及該catch塊內的另一個try塊等),或者編碼循環整個try塊(可能是最好的方法)。

2

這個怎麼樣:

int maxretries = 10; 
for (int i = 0; i < maxretries; i++) { 
    try { 
     display(); 
     break; 
    } catch (Exception e) { 
     // log exception 
     e.printStackTrace(); 
    } 
} 
+0

是的,我們也可以使用這個,謝謝 – MahiA

0

在下面的程序,我執行的時候重新運行指定的方法數,即使出現異常有5秒的時間差距。

public class ReExecuteMethod { 
    public static void main(String[] args) throws Exception { 

     int count = 0; 
     while (count <= 10) { 
      try { 
       rerun(); 
       break; 
      } catch (NullPointerException e) { 
       Thread.sleep(5000); 
       System.out.println(count); 
       count++; 
      } 

     } 
     System.out.println("Out of the while"); 
    } 

    static void rerun() { 
//  throw new NullPointerException(); 
     System.out.println("Hello"); 
    } 
} 
相關問題