Panic是一種我們用來處理錯(cuò)誤情況的機(jī)制。緊急情況可用于中止函數(shù)執(zhí)行。當(dāng)一個(gè)函數(shù)調(diào)用panic時(shí),它的執(zhí)行停止,并且控制流程到相關(guān)的延遲函數(shù)。
這個(gè)函數(shù)的調(diào)用者也會(huì)被終止,調(diào)用者的延遲函數(shù)也會(huì)被執(zhí)行(如果有的話)。這個(gè)過程一直持續(xù)到程序結(jié)束?,F(xiàn)在報(bào)告錯(cuò)誤情況。
這種終止序列稱為panic,可以由內(nèi)置函數(shù)recover控制。
package main import "os" func main() { panic("Error Situation") _, err := os.Open("/tmp/file") if err != nil { panic(err) } }
輸出:
panic: Error Situation goroutine 1 [running]: main.main() /Users/pro/GoglandProjects/Panic/panic example1.go:6 +0x39
package main import "fmt" func main() { fmt.Println("Calling x from main.") x() fmt.Println("Returned from x.") } func x() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in x", r) } }() fmt.Println("Executing x...") fmt.Println("Calling y.") y(0) fmt.Println("Returned normally from y.") } func y(i int) { fmt.Println("Executing y....") if i > 2 { fmt.Println("Panicking!") panic(fmt.Sprintf("%v" , i)) } defer fmt.Println("Defer in y", i) fmt.Println("Printing in y", i) y(i + 1) }
輸出:
Calling x from main. Executing x... Calling y. Executing y.... Printing in y 0 Executing y.... Printing in y 1 Executing y.... Printing in y 2 Executing y.... Panicking! Defer in y 2 Defer in y 1 Defer in y 0 Recovered in x 3 Returned from x.