go recover panic
tags: learning go programming
content
recoverhas to be put inside of a deferred function
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("all's good")
}
}
panic("No!")
}-
the above code works, because
defermeans the code will be run before the function returns, no matter what (even if the function panics) -
in the case where
recover()is not indefer- if
recoveris before panic, it doesn’t do anything cuz no panic yet - if it’s after panic, it won’t even be executed, cuz the code panics and passes the panic to the call stack before it could be executed
- if