Panic recovery is a mechanism in Go that allows a program to handle unexpected errors (panics) gracefully.
package main
import (
"fmt"
)
func mayPanic() {
// This function simulates a situation that causes a panic.
// For example, a division by zero.
panic("a problem occurred")
}
func safeCall() {
// Defer a function to recover from a panic.
defer func() {
if r := recover(); r != nil {
// r contains whatever was passed to panic()
fmt.Println("Recovered from panic:", r)
}
}()
// Call a function that may cause a panic.
mayPanic()
// This line will only be executed if the panic was successfully recovered.
fmt.Println("Function executed successfully.")
}
func main() {
safeCall()
// This line will be executed if the panic is recovered.
fmt.Println("Main function execution continues after safeCall.")
}
标签:function,defer,fmt,func,Go,recover,panic From: https://www.cnblogs.com/Answer1215/p/18009085