2011-05-03 69 views
0

我有這樣的Java代碼骨架 -異常處理的冒險III - 更新

 try { 
      Question q = null; //List of questions. I have put 3 in the list, in my main function 
      int i = 0; 
      while (i <= questions.size()) { 
       System.out.println("iteration " + i); 
       q = questions.get(i); 
       try { 
        try { 
         System.out.println("Script completed"); 
         break; 
        } catch (Exception e) { 
         // script is still executing... continue 
        } 
        //My entire logic is here.An exception is thrown in the first iteration 
        i++; 
       } catch (Exception e) { 
        //The thrown exception is caught here 
        try { 
        //The caught exception is handled here 
       } catch (IOException ioe) { 
        System.out.println("IO Exception.."); 
       } 
      } 
     } 
     } catch (IOException ioe) { 
      System.out.println("No more communication due to the lack of data"); 
     } catch (IllegalMonitorStateException imse) { 
      System.out.println("Illegal Monitor State Exception"); 
     } catch (IllegalThreadStateException itse) { 
      System.out.println("Illegal Thread State Exception"); 
     } 

而且輸出我得到的是有點像這樣 -

iteration 0 
//Exception handling related output 

iteration 0 //repeated because i++ doesn't happen since exception is thrown 
//Execution takes place normally 

iteration 1 
//???????? - Here is where i am facing the problem. I am not getting 

輸出完全。我知道爲什麼我仍然在第1次迭代(這與i ++有關,因爲第一次拋出異常而不會發生一次)。但任何人都可以幫助我如何成功執行此迭代呢?

+0

這裏絕對沒有足夠的信息 – 2011-05-03 13:17:18

+0

提供[SSCCE](http://sscce.org/)不僅可以幫助我們給出更好的答案,但構建它的過程可能會幫助您自己找到答案。試着在未來做到這一點! – 2011-05-03 13:18:41

+0

爲什麼在這個世界上你需要在這許多地方發現異常?像這樣嵌套的try塊是一個巨大的代碼異味 – 2011-05-03 13:24:24

回答

4

您需要檢查哪個catch塊在每次迭代中被執行。如果在//try3//try4(或者根本沒有異常拋出)中引發異常,則執行i++將執行

如果異常在//try2(無論是前//try3//catch4)拋出,然後i++不會執行。

+0

我知道什麼是hapening,但我試圖弄清楚如何克服這一點,不幸的是,我還沒有成功 – hari 2011-05-04 05:07:03