Golang errors

From wikinotes
Revision as of 01:13, 6 June 2022 by Will (talk | contribs) (Created page with "= panic and recover = <blockquote> Go seems to discourage the use of exception-style control-flows,<br> encouraging the use of errors in return-values instead. Go does provid...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

panic and recover

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

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
}