java - 如何在不使用“抛出 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?
解决方案
您可以调用该方法,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
}
}
推荐阅读
- python - 是否有一种有效/最佳的方式将数据从 BigQuery 表传输到 Elasticsearch?
- python - 如何通过类在 tkinter 中安排面板?
- php - PHP:检查加载的 TLS 证书是否可信
- list - Flutter ReorderableListView 与自定义对象
- azure-devops - 如何通过在 Azure DevOps 中运行查询来检索组织内的项目列表?
- reactjs - 图像加载后在 div 中滚动到底部
- docker-compose - 在 Docker Compose 中运行 Log stash 会引发错误
- python - Python 遍历浮点数组或列表
- c++ - 如何限制为 C++ 中的单个类创建的对象数量?
- google-sheets - Arrayformula 在对自己的列进行排序时中断(Google 表格)