Saturday 4 September 2021

Go Panic

 Go panic is a mechanism by which we handle error situations. Panic can be used to abort a function execution. When a function calls panic, its execution stops and the control flows to the associated deferred function.

The caller of this function also gets terminated and caller's deferred function gets executed (if present any). This process continues till the program terminates. Now the error condition is reported.

This termination sequences is called panicking and can be controlled by the built-in function recover.

Go Panic Example 1:

  1. package main  
  2.   
  3. import "os"  
  4.   
  5. func main() {  
  6.     panic("Error Situation")  
  7.     _, err := os.Open("/tmp/file")  
  8.     if err != nil {  
  9.         panic(err)  
  10.     }  
  11. }  

Output:

panic: Error Situation

goroutine 1 [running]:
main.main()
/Users/pro/GoglandProjects/Panic/panic example1.go:6 +0x39

Go Panic Example 2

  1. package main  
  2.   
  3. import "fmt"  
  4. func main() {  
  5.     fmt.Println("Calling x from main.")  
  6.     x()  
  7.     fmt.Println("Returned from x.")  
  8. }  
  9. func x() {  
  10.     defer func() {  
  11.         if r := recover(); r != nil {  
  12.             fmt.Println("Recovered in x", r)  
  13.         }  
  14.     }()  
  15.     fmt.Println("Executing x...")  
  16.     fmt.Println("Calling y.")  
  17.     y(0)  
  18.     fmt.Println("Returned normally from y.")  
  19. }  
  20.   
  21. func y(i int) {  
  22.     fmt.Println("Executing y....")  
  23.     if i > 2 {  
  24.         fmt.Println("Panicking!")  
  25.         panic(fmt.Sprintf("%v" , i))  
  26.     }  
  27.     defer fmt.Println("Defer in y", i)  
  28.     fmt.Println("Printing in y", i)  
  29.     y(i + 1)  
  30. }   

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.


No comments:

Post a Comment