panic是一种我们用来处理错误情况的机制。紧急情况可用于中止函数执行。当一个函数调用panic时, 它的执行停止, 并且控制流到相关的延迟函数。
此函数的调用方也将终止, 并且调用方的延迟函数将被执行(如果存在)。该过程一直持续到程序终止。现在报告错误情况。
此终止序列称为panic, 可以通过内置的功能restore控制。
panic示例1:
package mainimport "os"func main() {
panic("Error Situation")
_, err := os.Open("/tmp/file")
if err != nil {
panic(err)
}
}
输出:
panic: Error Situationgoroutine 1 [running]:
main.main()
/Users/pro/GoglandProjects/Panic/panic example1.go:6 +0x39
panic示例2
package mainimport "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)
}
【Go panic使用】输出:
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.