Panic是一种我们用来处理错误情况的机制。紧急情况可用于中止函数执行。当一个函数调用panic时,它的执行停止,并且控制流程到相关的延迟函数。
这个函数的调用者也会被终止,调用者的延迟函数也会被执行(如果有的话)。这个过程一直持续到程序结束。现在报告错误情况。
这种终止序列称为panic,可以由内置函数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.