Golang errors: Difference between revisions
From wikinotes
(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...") |
No edit summary |
||
Line 1: | Line 1: | ||
Go seems to discourage the use of exception-style control-flows,<br> | Go seems to discourage the use of exception-style control-flows,<br> | ||
encouraging the use of errors in return-values instead. | encouraging the use of errors in return-values instead. | ||
= panic and recover = | |||
<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. | ||
<syntaxhighlight lang="go"> | <syntaxhighlight lang="go"> |
Revision as of 01:18, 6 June 2022
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-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 }