Advertisement
cydside

Panic Handle Example

Nov 27th, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 0.44 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "log"
  6. )
  7.  
  8. func main() {
  9.     defer func() {
  10.         if err := recover(); err != nil {
  11.             log.Println("panic arrived in main:", err)
  12.         }
  13.     }()
  14.  
  15.     divideByZero()
  16.     fmt.Println("we survived dividing by zero!")
  17.  
  18. }
  19.  
  20. func divideByZero() {
  21.     defer func() {
  22.         if err := recover(); err != nil {
  23.             log.Println("panic occurred:", err)
  24.         }
  25.     }()
  26.     fmt.Println(divide(1, 0))
  27. }
  28.  
  29. func divide(a, b int) int {
  30.     return a / b
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement