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?
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.