我有以下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 ++有关,由于第一次抛出的异常,它不会发生一次)。但是,任何人都可以帮助我如何成功执行此迭代吗?
答案 0 :(得分:4)
您需要检查在每次迭代中执行哪个 catch
块。如果在//try3
或//try4
中抛出异常(或者根本没有抛出异常),则i++
将执行。
如果在//try2
(之前 //try3
或之后 //catch4
之后引发了异常,那么{{1} 不会执行。