How to go from catch block to try block in java?

2020-05-09 17:28发布

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

Example

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

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?

1条回答
2楼-- · 2020-05-09 18:08

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
    }
}

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.

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.

查看更多
登录 后发表回答