Eri*_*ric 6 java exception-handling exception
在我的Java代码中,我有一个函数调用getAngle(),有时会抛出一个NoAngleException.下面的代码是编写一个函数的最佳方法,该函数一直调用getAngle()直到没有抛出异常?
public int getAngleBlocking()
{
while(true)
{
int angle;
try
{
angle = getAngle();
return angle;
}
catch(NoAngleException e)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者重写错误后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
Run Code Online (Sandbox Code Playgroud)
这是假设在此期间过程之外的某些事情发生了变化.通常,这样的事情将用于重新连接:
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
Run Code Online (Sandbox Code Playgroud)
我想你应该调查为什么getAngle()抛出异常然后解决问题.如果这是随机的,比如来自传感器的输入,也许你应该再等一段时间再打电话.你也可以使getAngle()阻塞,这意味着getAngle()会等到获得好的结果.
忽略你如何解决你的问题,你应该有一些超时机制,所以你不会在一个无限循环中结束.当然,这假设您不希望有可能无限循环.