异常处理冒险III - 更新

时间:2011-05-03 13:11:15

标签: java exception-handling try-catch

我有以下java代码骨架 -

        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 ++有关,由于第一次抛出的异常,它不会发生一次)。但是,任何人都可以帮助我如何成功执行此迭代吗?

1 个答案:

答案 0 :(得分:4)

您需要检查在每次迭代中执行哪个 catch块。如果在//try3//try4中抛出异常(或者根本没有抛出异常),则i++ 执行。

如果在//try2之前 //try3之后 //catch4之后引发了异常,那么{{1} 不会执行。