Golang errors

From wikinotes
Revision as of 01:18, 6 June 2022 by Will (talk | contribs)

Go seems to discourage the use of exception-style control-flows,
encouraging the use of errors in return-values instead.

panic and recover

Go does provide panic, which is similar to exceptions except that they are untyped.

panic("I encountered an error")  // raise a panic

err := recover() // returns nil/error-msg-if-present

Panics behave similar to exceptions, blocking all parent-callers once raised unless it is handled.

It is common to handle panics in deferred functions

func main() {
    fmt.Println("hi")
    panic("I just encountered an error")
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("Error: ", err)
            panic(err)                         // <<-- re-raise panic
        }
    }

    fmt.Println("bye")  // <-- never runs
}