How to raise error and alter the control of the flow to desired line

How to transfer control to a specific line of code by raising error ? Following is the example scenario
https://play.golang.org/p/Ibdy0qibeNJ

package main

import (
    "errors"
    "fmt"
)

func doSomething() {
    fmt.Println("Doing Something")

}

func doRun() {
    fmt.Println("Doing Running")

}

func doPlay() {
    fmt.Println("Doing Playing")

}

func doEat() {

    fmt.Println("Doing Eating")
    doEatNoodles()
            //create an error
    e: = errors.New("Too Lazy!! Donot want to execute the rest of the code..take me back to the end of 
 the flow please!!")

    ErrorFound(e)
    doEatBread()

}
 func doEatNoodles() {
    fmt.Println("Doing noodles eating")

}

func doEatBread() {
    fmt.Println("Doing Bread eating")

}

func ErrorFound(err error) {
    if err != nil {
            //How should I throw an error here so that the flow gets stopped and doPlay() is not called 
instead the control print
    }

}
func main() {

    //the goal is that if there is an error then the control should stop executing the flow and should go to t 
the last line saying the flow ends here

    fmt.Println("Flow Starts Here")

    //the flow starts here

    doSomething()
    doRun()
    doEat()
    doPlay()

    //the flow ends here

    fmt.Println("Flow Ends Here")

}
1 Like

Hi, @altu_faltu, Do you want to sometimes not execute the logic or never execute it? If sometimes, use an if to check for the condition to stop executing and return an error. If you never want to run the code, then remove it or I guess you could wrap it in if false { ... }, but that seems like a bad idea to me.

1 Like

I want to make sure if there is an error encountered, instead of propagating the error to its parent and then to its grandparent and further more up the stack if there is any mechanism to throw this error and catch the error after the flow.It helps not to wrote return error statements for every function call

1 Like

You can use panic. See here how it is used.

But note that this is not how errors are handled in Go. Your functions should return an error and the caller should handle the error as appropriate. You are looking for exceptions, but they are not supported in Go. The closest to exception is panic. But use of panic in this way is discouraged.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.