English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Panic is a mechanism we use to handle error situations. Emergencies can be used to stop the execution of a function. When a function calls panic, its execution stops, and the control flow goes to the relevant deferred functions.
The caller of this function will also be terminated, and the deferred functions of the caller will be executed (if any). This process continues until the program ends. Now report the error situation.
This termination sequence is called panic, which can be controlled by the built-in function recover.
package main import "os" func main() { panic("Error Situation") _, err := os.Open("/tmp/file) if err != nil { panic(err) } }
Output:
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) }
Output:
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.