0
package main

import "time"

func main() {
    // infinite loop
    for {

        for i := 0; i < 2; i++ {

            conn, err := opentsdb.OpenConnection()

            if err {
                time.Sleep(10 * time.Second)
            }

        }
    }
}

I need Program will execute from the beginning if an error block occur.

How to handle it?

1
  • You're correct-- your for loop will run forever. What's the requirement? Do you want the program to exit if there's an error? The question is unclear about what you want to do. "Handle it" can mean a variety of things. Commented Jun 2, 2016 at 14:57

1 Answer 1

7

Using goto is a common way to handle error flows in a nested loop

func main() {
RESTART:
    for {
        for i := 0; i < 2; i++ {
            conn, err := opentsdb.OpenConnection()
            if err {
                time.Sleep(10 * time.Second)
                goto RESTART
            }
        }
    }
}

If you only want to restart the outer loop, and there's nothing between the RESTART label and the for loop, you can use continue RESTART to continue the loop at the RESTART label. In this simple case, just using break will continue the outer loop as well.

Sign up to request clarification or add additional context in comments.

1 Comment

@icza: yes, that works here too. I just assumed such a trivial example probably was missing other logic in there, otherwise you could also just break here too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.