How to handle errors that occur during defer in Golang?

WBOY
Release: 2024-06-02 22:20:59
Original
1110 people have browsed it

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)
}
Copy after login

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")
}
Copy after login

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 操作 ...
}
Copy after login

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 操作 ...
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!