Go panic and recover

Go lacks the traditional try/catch mechanism for exception handling, opting for a more concise approach: throwing a panic exception and capturing it with recover within a defer statement. This exception handling mechanism allows programs to gracefully handle or terminate upon encountering severe errors, rather than simply crashing and exiting.

Characteristics of panic

  1. panic is a built-in function used to trigger a runtime error within the program
  2. When panic is called, it immediately halts the execution of the code following it (within the current function)
  3. If any defer functions are defined within that function, they are executed in LIFO order
  4. If no code calls recover to recover from the panic, the entire program terminates

Characteristics of recover

  1. recover is a built-in function used to capture a panic within a defer function and resume normal program execution
  2. recover can only be called within a defer function and is only effective within the function where the panic occurred
  3. The defer function containing recover must be defined before the panic is called
  4. If recover is called when no panic is in progress, it returns nil
func main() {  
    defer func() {
        if err := recover(); err != nil {
            fmt.Println("Recovered from panic:", err)
        }
    }()
    
    fmt.Println("Start...")
    defer fmt.Println("Deferred...") //multiple defer statements, executed in LIFO Order
    panic("Something went wrong...")
    fmt.Println("Logic after panic.") //no further code is executed after panic triggered 
}

#Start...
#Deferred...
#Recovered from panic: Something went wrong…

After a panic is triggered, no further code within the function (beyond the point of the panic) is executed. However, any defer statements that have already been encountered (i.e., defined before the panic) are executed in LIFO order. This allows for cleanups and potentially recovering from the panic if a recover call is present in one of the defer functions.

Take a break

👉👉👉 【BTTH Year EP98】Heaven Mountain Blood Pool story opened. Feng Qing'er is comming...