一、子協程的panic,只能在子協程中處理
下面的代碼,main 函數 無法獲取panic
package main
import (
"fmt"
"time"
)
func main() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
go test()
time.Sleep(time.Second)
}
func test() {
test1()
}
func test1() {
panic("我錯了")
}
二、子協程處理panic
package main
import (
"fmt"
"time"
)
func main() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
go test()
time.Sleep(time.Second)
}
func test() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
test1()
}
func test1() {
panic("我錯了")
}
三、一個協程中才能后獲取panic,最上層的能夠獲取下面的panic
如下代碼main函數可以獲取test1 函數中的panic
package main
import (
"fmt"
)
func main() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
test()
}
func test() {
defer func() {
if e := recover(); e != nil {
fmt.Println(e)
}
}()
test1()
}
func test1() {
panic("我錯了")
}