如何从catch块转到Java中的尝试块? [英] How to go from catch block to try block in java?

查看:90
本文介绍了如何从catch块转到Java中的尝试块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在try块中有一些逻辑。如果出现异常,那么我将在catch块中捕获异常。

I have some logic inside the try block. If exception arises, then I am catching the exception in the catch block.

示例

try{
    // line 1
}catch(SocketException se){
    // again goto try block
}

如果控件进入catch块,那么我想再次在try块中执行第1行,但是如何再次尝试try块?我们可以使用Label吗?

If control comes inside catch block then again I want to execute line 1 in try block but how to go again try block? Can we use Label?

推荐答案

如果您想循环回到代码的较早位置,请将代码循环

If you want to loop back to an earlier point in your code, put your code in a loop.

while (true) {
    try {
        // line 1 (something that might throw an exception)
        break;
    } catch (SocketException se) {
        // handle the error
    }
}

如果您的 try 块中的代码成功执行,将遇到 break ,您的循环将退出。如果抛出 SocketException ,执行将返回 while 循环的顶部以及您的第1行将重复。

If the code in your try block executes successfully, the break will be encountered, and your loop will exit. If a SocketException is thrown, execution will return the the top of the while loop and your line 1 will be repeated.

如果您只想重试固定次数(以避免无限期卡死),则可以使用 for 循环而不是 while 循环。

If you only want to retry a fixed number of times (to avoid being stuck indefinitely), then you could use a for loop instead of a while loop.

这篇关于如何从catch块转到Java中的尝试块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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