Home >Backend Development >Golang >How to handle errors that occur during defer in Golang?
There are two ways to handle errors in defer in Go: 1. Create a custom error type to catch errors; 2. Use recover() to catch panics. For example, using recover() to capture errors in defer can be written like this: defer func() { if err := recover(); err != nil { fmt.Println(err) } }.
In Golang, the defer
statement is used to ensure that the operations in the function are executed immediately after the function returns, regardless of whether an exception occurs. However, if errors occur during the execution of a defer
function, these errors are usually ignored.
To handle errors during defer
, there are two main ways:
One way is to create a custom error Type to catch errors in defer
functions. For example:
import ( "fmt" ) type DeferError struct { err error } func (e DeferError) Error() string { return fmt.Sprintf("Defer error: %v", e.err) }
recover()
Another way is to use recover()
to capture the defer
function panic. For example:
import "fmt" func main() { defer func() { if err := recover(); err != nil { fmt.Println(err) } }() panic("defer error") }
Consider the following example:
import ( "fmt" "os" ) func writeToFile(filename string) { defer os.Remove(filename) // 删除文件 f, err := os.Create(filename) if err != nil { panic(fmt.Sprintf("Error creating file: %v", err)) } // 执行 IO 操作 ... }
In this example, the defer
function is used to ensure that the file is deleted after the function returns . However, if the file creation fails (os.Create
error), the defer
function will not execute because the function will return early.
To catch this error, we can use the following method:
func writeToFile(filename string) { defer func() { if err := recover(); err != nil { fmt.Println(err) } os.Remove(filename) // 删除文件 }() f, err := os.Create(filename) if err != nil { panic(fmt.Sprintf("Error creating file: %v", err)) } // 执行 IO 操作 ... }
Now, if the file creation fails, the defer
function will still be executed because it does not throw an exception.
The above is the detailed content of How to handle errors that occur during defer in Golang?. For more information, please follow other related articles on the PHP Chinese website!