Golang errors: Difference between revisions
From wikinotes
No edit summary |
|||
Line 2: | Line 2: | ||
encouraging the use of errors in return-values instead. | encouraging the use of errors in return-values instead. | ||
= panic | = panic / recover = | ||
<blockquote> | <blockquote> | ||
Go does provide <code>panic</code>, which is similar to exceptions except that they are untyped. | Go does provide <code>panic</code>, which is similar to exceptions except that they are untyped. |
Revision as of 15:47, 6 June 2022
Go seems to discourage the use of exception-style control-flows,
encouraging the use of errors in return-values instead.
panic / 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-presentPanics 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 }