基本用法
- recover 位置,需要与 panic 在同一个 goroutine 中
package main
import (
"fmt"
"time"
)
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Recover in main from error:", err)
}
fmt.Println("Execution finished")
}()
go func() {
panic("panic in goroutine")
}()
time.Sleep(1 * time.Second)
}
package main
import (
"fmt"
)
func main() {
defer func() {
defer func() {
if err := recover(); err != nil {
fmt.Println("Recover from error:", err)
}
}()
if err := recover(); err != nil {
fmt.Println("Recover from error:", err)
panic("again")
}
}()
panic("whatever")
}