简体   繁体   中英

In Java, when catching an exception, returning to for loop

Is it possible to return to a loop if an exception is thrown?

Lets say my code is:

try {
     for(int i=0; i < a.length; i++) {
          sysout(a[i])
     } 
} catch (Exception e) {
     sysout("Error")
}

And I want to the loop to resume where it stopped.

this way

for (int i = 0; i < a.length; i++)
    try {
        sysout(a[i]);
    } catch (Exception e)  {
        sysout("Error");
    }
}

Don't use

for(int i=0; i<a.length; i++) 

Use

for(int i = startIndex; i<a.length; i++) 

and you can guess you need to initialize startIndex to 0 and set it to the loop value on exception so the next time you enter the loop it starts at startIndex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM