gpt4 book ai didi

java - 在 Java 中,继续调用函数直到没有异常抛出的最佳方式是什么?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:41:16 26 4
gpt4 key购买 nike

在我的 Java 代码中,我有一个名为 getAngle() 的函数,它有时会抛出一个 NoAngleException。以下代码是否是编写一个不断调用 getAngle() 直到没有异常抛出的函数的最佳方式?

public int getAngleBlocking()
{
while(true)
{
int angle;
try
{
angle = getAngle();
return angle;
}
catch(NoAngleException e)
{

}
}
}

或者重写 getAngle() 以在出错时返回 NaN 是更好的主意吗?

最佳答案

我很惊讶地阅读了这个线程的一些答案,因为这种情况正是检查异常存在的原因。你可以这样做:

private final static int MAX_RETRY_COUNT = 5;

//...

int retryCount = 0;
int angle = -1;

while(true)
{
try
{
angle = getAngle();
break;
}
catch(NoAngleException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getAngle().", e);
}

// log error, warning, etc.

retryCount++;
continue;
}
}

// now you have a valid angle

这是假设流程之外的某些事情同时发生了变化。通常,重新连接时会执行类似这样的操作:

private final static int MAX_RETRY_COUNT = 5;

//...

int retryCount = 0;
Object connection = null;

while(true)
{
try
{
connection = getConnection();
break;
}
catch(ConnectionException e)
{
if(retryCount > MAX_RETRY_COUNT)
{
throw new RuntimeException("Could not execute getConnection().", e);
}

try
{
TimeUnit.SECONDS.sleep(15);
}
catch (InterruptedException ie)
{
Thread.currentThread().interrupt();
// handle appropriately
}

// log error, warning, etc.

retryCount++;
continue;
}
}

// now you have a valid connection

关于java - 在 Java 中,继续调用函数直到没有异常抛出的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com