简体   繁体   English

Java循环抛出异常的方法

[英]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. 我有一个方法,如果array [x] [y]单元格不为空,则会引发异常: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. 我需要运行该方法,如果它引发异常,则需要重新运行它,直到找到一个空单元为止,最多5次。
If it doesnt find an empty cell within 5 times, it has to clean the array, and then re-run!! 如果它在5次内未找到空单元,则必须清理阵列,然后重新运行!

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. 但是,这可能是XY问题 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. 例外是特殊的程序条件,而不是正常操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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