您如何实施重试? [英] How do you implement a re-try-catch?

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

问题描述

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。我不认为我们打电话来记录异常。我的东西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返回真的,那我们再试一次。鉴于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 code> 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;
    }
}

我采取了 / code>和 maxTries 以避免运行到无限循环,以防您的 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天全站免登陆