示例1
// hello.go
package main
import "fmt"
func main() {
panic("出现错误")
fmt.Println("Hello")
}
执行结果:
panic: 出现错误
goroutine 1 [running]:
main.main()
/path/to/hello.go:7 +0x39
示例2
// hello.go
package main
import "fmt"
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Printf("接收错误: %v", err)
}
}()
panic("错误")
fmt.Println("Hello")
}
执行结果:
接收错误: 错误
示例3
// hello.go
package main
import "fmt"
func main() {
defer func() {
if err := recover(); err != nil {
fmt.Printf("接收错误: %v", err)
}
}()
defer func() {
panic("错误")
}()
fmt.Println("Hello")
}
执行结果:
Hello
接收错误: 错误
recover() 必须在 panic 之前调用,否则,会无效:
// hello.go
package main
import "fmt"
func main() {
defer func() {
panic("错误")
}()
defer func() {
if err := recover(); err != nil {
fmt.Printf("接收错误: %v", err)
}
}()
fmt.Println("Hello")
}
执行结果:
Hello
panic: 错误
goroutine 1 [running]:
main.main.func1()
/path/to/hello.go:8 +0x39
main.main()
/path/to/hello.go:18 +0xb7