Golang例子:异常处理,Panic和Recover
Go provides us with the ability to regain control after panic has occurred. The built-in recover() function is called from within a defer to check if a panic happened.
The signature of the recover() function is as follows:
func recover() interface{}
The recover() function accepts no arguments and returns an empty interface{}. Capturing a panic in a deferred function is standard practice in Go.
Example
package main
import (
"errors"
"fmt"
)
var result = 1
func chain(n int) {
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
}
}()
if n == 0 {
panic(errors.New("Cannot multiply a number by zero"))
} else {
result *= n
fmt.Println("Output: ", result)
}
}
func main() {
chain(5)
chain(2)
chain(0)
chain(8)
}
We have used r := recover() to detect any occurrence of panic in our program and assign the panic message to r. We call recover within an if statement and check to see if a non-nil value was found. We must call recover from within a defer because once a panic happens, only deferred functions are executed.
Running this code produces the following output:
Output: 5
Output: 10
Cannot multiply a number by zero
Output: 80