Home  >  Article  >  Backend Development  >  How to handle errors that occur during defer in Golang?

How to handle errors that occur during defer in Golang?

WBOY
WBOYOriginal
2024-06-02 22:20:591127browse

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) } }.

如何在 Golang 中处理 defer 期间发生的错误?

How to handle errors that occur during defer in Golang?

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:

Custom Error Types

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)
}

Use 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")
}

Practical case

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn