Home > Backend Development > Golang > When will golang defer be executed?

When will golang defer be executed?

(*-*)浩
Release: 2019-12-03 10:00:45
Original
2634 people have browsed it

When will golang defer be executed?

Golang has a special control statement, which is defer. The defer statement is used to delay calling the specified function, such as releasing resources, etc. It will be executed at the end of the function, but Before Return, , let's take a brief understanding of the code: (Recommended learning: Go )

package main

func main() {
    test()
}func test() {
    println("test1")    defer func() {
        println("defer test2")
    }()
    println("test3")
}
Copy after login

## The execution results are as follows: ## 在##It is clear that the function with defer is executed last

Now change the code to make the code panic. When an exception is thrown, will the defer delay function still be executed?

test1
test3
defer test2
Copy after login
Output

package main

func main() {
    test()
}func test() {

    println("test1")
        panic("panic")    defer func() {
        println("defer test2")
    }()
    
    println("test3")
}
Copy after login
The delay function is not executed. Why is this? It’s because panic is before the delay function. Change the code as follows

test1
panic: panic
Process finished with exit code 2
Copy after login

Output

package main

func main() {
    test()
}func test() {

    println("test1")    defer func() {
        println("defer test2")
    }()
    panic("panic")
    println("test3")
}
Copy after login
The delay function is executed and you can see panic The delayed function cannot be executed before the delayed function, after all, an exception will be thrown.

The above is the detailed content of When will golang defer be executed?. 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