關於panic ,主協程的recover 是無法獲取 子協程的panic 的


一、子協程的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("我錯了")
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM