你如何实现重试捕获? [英] How do you implement a re-try-catch?

查看:26
本文介绍了你如何实现重试捕获?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Try-catch 旨在帮助异常处理.这意味着它会以某种方式帮助我们的系统更加健壮:尝试从意外事件中恢复.

Try-catch is meant to help in the exception handling. This means somehow that it will help our system to be more robust: try to recover from an unexpected event.

我们怀疑在执行和指令(发送消息)时可能会发生一些事情,所以它被包含在 try 中.如果发生了几乎出乎意料的事情,我们可以做点什么:我们编写捕获.我不认为我们打电话只是记录异常.我认为 catch 块是为了让我们有机会从错误中恢复.

We suspect something might happen when executing and instruction (sending a message), so it gets enclosed in the try. If that something nearly unexpected happens, we can do something: we write the catch. I don't think we called to just log the exception. I thing the catch block is meant to give us the opportunity of recovering from the error.

现在,假设我们从错误中恢复,因为我们可以修复错误.重试可能会非常好:

Now, let's say we recover from the error because we could fix what was wrong. It could be super nice to do a re-try:

try{ some_instruction(); }
catch (NearlyUnexpectedException e){
   fix_the_problem();
   retry;
}

这将很快陷入永恒循环,但假设 fix_the_problem 返回 true,然后我们重试.鉴于Java中没有这样的东西,你将如何解决这个问题?解决这个问题的最佳设计代码是什么?

This would quickly fall in the eternal loop, but let's say that the fix_the_problem returns true, then we retry. Given that there is no such thing in Java, how would YOU solve this problem? What would be your best design code for solving this?

这就像一个哲学问题,因为我已经知道 Java 不直接支持我的要求.

This is like a philosophical question, given that I already know what I'm asking for is not directly supported by Java.

推荐答案

你需要像这样将你的 try-catch 包含在一个 while 循环中:-

You need to enclose your try-catch inside a while loop like this: -

int count = 0;
int maxTries = 3;
while(true) {
    try {
        // Some Code
        // break out of loop, or return, on success
    } catch (SomeException e) {
        // handle exception
        if (++count == maxTries) throw e;
    }
}

我采用了 countmaxTries 来避免陷入无限循环,以防在您的 try 块 中不断发生异常.

I have taken count and maxTries to avoid running into an infinite loop, in case the exception keeps on occurring in your try block.

这篇关于你如何实现重试捕获?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆