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

最佳答案

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

如果在//try2中(在//try3之前或//catch4之后)引发异常,则将不执行i++

关于java - 异常处理冒险III-更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5869957/

10-11 22:47
查看更多