2011-05-03 41 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