首页 > 解决方案 > 如何在不使用“抛出 XXXException”的情况下处理“未处理的异常”

问题描述

我有一项任务需要在不使用“抛出 XXXException”的情况下处理“未处理的异常”。情况如下:

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

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

在我的发送方法中,我调用了 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() 上没有 JMSException?

标签: javaexception

解决方案


您可以调用该方法,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
    }
}

推荐阅读