简体   繁体   中英

Java looping a method if it throws exception

I have a method that if the array[x][y] cell is not empty, throws an exception: CellNotEmptyException.

I need to run that method, and if it throws the exception, i need to re-run it, until it will find an empty cell, and for a max of 5 times.
If it doesnt find an empty cell within 5 times, it has to clean the array, and then re-run!!

Is there a way? Thank you

// loop forever until TheMethod() succeeds

while (true)
{
    try
    {
        TheMethod();
        break;
    }

    catch (Exception e)
    {
    }
}

This might be an XY-problem situation, though. Iteratively calling a function until a cell is found doesn't sound like a great design to me. And throwing an exception is slow, so if this is a "normal" behavior of your program, consider some other mechanism than exceptions for finding an empty cell. Exceptions are for exceptional program conditions, not normal operation.

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