Home >Backend Development >Golang >How to recover from panic in Golang?
In Go, use the recover function to recover from a panic, which returns the most recent panic value from the function stack. In actual combat, you can handle io.EOF exceptions, for example: open a file and use defer to catch panic. If panic is equal to io.EOF, exit normally, otherwise panic will occur.
In Golang, panic
will cause the program to exit abnormally. Although panic
is useful for handling unrecoverable errors, there are situations where you may want to recover and continue execution.
Use the recover
function to recover from panic
. recover
will return the latest panic
information from the current function function stack, and return a panic value of type interface{}
.
func main() { // 包装可能会产生 panic 的代码 defer func() { if err := recover(); err != nil { // 处理 panic fmt.Println("recovered from panic:", err) } }() // 可能产生 panic 的代码 panic("this will cause a panic") }
Practical case
The following is an example of handling io.EOF
exception when reading data from a file:
package main import ( "fmt" "io" "os" ) func main() { f, err := os.Open("data.txt") if err != nil { panic(err) } defer f.Close() defer func() { if err := recover(); err != nil { if err == io.EOF { fmt.Println("reached end of file") } else { panic(err) } } }() // 读取数据 data := make([]byte, 1024) for { n, err := f.Read(data) if err != nil { if err == io.EOF { // 达到文件末尾,正常退出 break } else { // 其他错误,引发 panic panic(err) } } // 处理读取到的数据 } }
The above is the detailed content of How to recover from panic in Golang?. For more information, please follow other related articles on the PHP Chinese website!