By using the recover() function, you can capture panics in the current function context, prevent program crashes and handle errors gracefully: recover() returns nil when no panic occurs, and when an uncaught panic occurs or recovers from the function where the panic occurred Returns the panic value. Add defer callbacks around function calls to catch panics and perform custom handling, such as logging error information. recover() only captures panics in the current function context, does not cancel panics, and only works on unhandled errors.
How to use Golang’s recover() function to deal with panic
Introduction
Panic is a special error handling mechanism in the Go language. When the program encounters an error that cannot be handled, it will cause the program to crash. recover()
The function can catch and handle panics, allowing the program to recover from errors gracefully.
recover()
Function
recover()
function is a built-in function that can be captured from the current function context Recent panic. It is returned if:
If no panic occurs, recover()
will return a nil
value.
Practical case
Consider a function that reads a file. The function may have the following errors:
func readFile(filename string) ([]byte, error) { data, err := os.ReadFile(filename) if err != nil { return nil, err } return data, nil }
To use recover( )
function to catch this error, you can add a defer
statement around the calling function:
func main() { defer func() { if err := recover(); err != nil { log.Printf("捕获到恐慌: %v", err) } }() _, err := readFile("non-existent-file.txt") if err != nil { log.Printf("读取文件出错:%v", err) } }
When the program tries to read a file that does not exist, a panic will occur and then defer
The recover()
function in the callback captures the panic. This allows the program to log errors and exit gracefully.
Note
recover()
can only capture panics from the current function context, so if the panic occurs in a nested function , it cannot be captured. recover()
function does not cancel the panic, which means that the program will continue to crash even if the panic is caught. recover()
The function should only be used to handle unhandled errors and should not replace normal error handling mechanisms. The above is the detailed content of How to use Golang's recover() function to handle panics?. For more information, please follow other related articles on the PHP Chinese website!