Go: Recover from a panic
A panic is caused either by a runtime error or an explicit call to the built-in panic
function.
A program recovers from a panic by calling the built-in function recover
, after which normal execution is resumed. Since all the functions ordinary code is skipped during a panic, the only chance you have to call recover
is from within a deferred function.
The recover
function returns whatever you gave as argument to the panic
function. (During normal operation it will return nil
.)
Another example
func main() {
s := foo()
fmt.Printf("main received: %q\n", s)
}
func foo() string {
defer func() {
if err := recover(); err != nil {
fmt.Printf("recovering from: %q\n", err)
}
}()
s := "before"
panic("disaster")
s += " after"
return s
}
Output:
recovering from: "disaster"
main received: ""
Since the panic occured before foo
returned a value, s
in main
still has its initial zero value ""
:
Return a value
To return a value during a panic, use a named return value:
func main() {
s := foo()
fmt.Printf("main received: %q\n", s)
}
func foo() (s string) {
defer func() {
if err := recover(); err != nil {
fmt.Printf("recovering from: %q\n", err)
s += " during"
}
}()
s = "before"
panic("disaster")
s += " after"
return s
}
Output:
recovering from: "disaster"
main received: "before during"
Comments
Be the first to comment!