如何在不使用"throws XXXException"的情况下处理"Unhandled Exception"



我有一个任务,需要在不使用"throws XXXException"的情况下处理"Unhandled Exception"。情况如下:

如果一个方法抛出JMSException,我需要重试它。

public void retry(int retryCount) throws MessageGatewayException, JMSException {
restartConnection(); //
}
public void restartConnection() throws JMSException {
init(); //this is where JMSException is thrown
}

在我的send方法中,我调用retry((。

public void send(int retryCount) throws MessageGatewayException {
//exit method if retried enough times.
if(retryCount > someNumber)
throw new IllegalArgumentException();
try {
producer.send();
}
catch (JMSException e) {
retry(retryCount); // this is where Unhandled Exception is.
}
}

我想做的是,当从send((调用retry((时,如果restartConnection((失败并引发JMSException,我希望retry(((调用send(retryCount++(。我不想在send((方法上添加JMSException,但它说我需要实现它。有没有办法处理这个异常,这样我就不会在send上有JMSExcession?

您可以用retryCount+1调用该方法,但当您达到例如10时,会引发异常以避免无限错误

send中处理

public void send(int retryCount) throws MessageGatewayException {
//exit method if retried enough times.
if(retryCount > someNumber)
throw new IllegalArgumentException();
try {
producer.send();
}
catch (JMSException e) {
try {
retry(retryCount); // this is where Unhandled Exception is
}catch (JMSException ex) {
if(retryCount < 10)
send(retryCount+1);
else
logger.error(e); // or print or whatever
}
}
}

retry:中处理

public void retry(int retryCount) throws MessageGatewayException{
try{
restartConnection(); //
}catch (JMSException e) {
if(retryCount < 10)
retry(retryCount+1);
else
logger.error(e); // or print or whatever
}
}

所以我找到了一种方法来处理这个问题,但我不确定这是正常的做法

public void send(int retryCount) throws MessageGatewayException {
//exit method if retried enough times.
if(retryCount > someNumber)
throw new IllegalArgumentException();
try {
producer.send();
}
catch (JMSException e) {
try {
retry(retryCount); // this is where Unhandled Exception is
}
catch (JMSException ex) {
send(++retryCount);
}
}
}

所以我基本上是在我的catch块里面使用另一个try/catch块。这确实消除了错误,而且效果很好,但我不确定这是怎么回事。

似乎需要保留retry方法中包含的重试逻辑。这假设send的初始retryCount参数是"尝试的最大重试次数"。

public void retry(int retryCount) throws MessageGatewayException {
while (retryCount-- > 0 && !restartConnection());
}

并将布尔结果添加到restartConnection:

public boolean restartConnection() {
try {
init(); 
return true;
} catch (JMSException e) {
return false;
}
}

您的send方法在本例中保持不变。

最新更新