Panic和Recover
panicrecoverpanicPanic
FpanicFFFFpanicpanicgoroutinepanicRecover
goroutinerecoverrecovernilgoroutinerecoverpanicpanicvar user = os.Getenv("USER")
func init() {
if user == "" {
panic("no value for $USER")
}
}panicfunc throwsPanic(f func()) (b bool) {
defer func() {
if x := recover(); x != nil {
b = true
}
}()
f() //执行函数f,如果f中出现了panic,那么就可以恢复回来
return
}最容易理解就是给个例子,文章里有例子:
package main
import (
"fmt"
//"os"
)
var user = ""
func inita() {
defer func() {
fmt.Print("defer##\n")
}()
if user == "" {
fmt.Print("@@@before panic\n")
panic("no value for user\n")
fmt.Print("!!after panic\n")
}
}
func throwsPanic(f func()) (b bool) {
defer func() {
if x := recover(); x != nil {
fmt.Print(x)
b = true
}
}()
f()
fmt.Print("after the func run")
return
}
func main() {
throwsPanic(inita)
}执行结果:
D:\go>go run b.go
@@@before panic
defer##
no value for user
如上面所说的:
panicuser=""fmt.Print("!!after panic\n")defer##deferRecoverpanicno value for user