Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Go Deferred function call again in error panic block

I think the question is pretty clear once you look at the following setup?

config := database.NewConfig()
connection := database.Connect(config)
defer connection.Destroy()

...

err = app.Listen(address)
if err != nil {
    connection.Destroy() // Do i need this?
    panic(err)
}

... // defer connection.Destroy() is called 

Do i have to call the deferred function in an error case of panic(err) because thats in a new block and therefore in a different scope?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Do i have to call the deferred function in an error case of panic(err) because thats in a new block and therefore in a different scope?

No, for two reasons: (1) defer operates at the level of the function, not the level of the block (so in this respect it differs from the scope of local variables); and (2) the invocation happens whenever the surrounding function returns, even if it’s "returning" only because it called some function that ended up panicking.

As the specification puts it:

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

(In particular, note that the bit about panicking has to do with the goroutine panicking, rather than worrying about exactly which function triggered the panic.)

I recommend bookmarking the specification and consulting it when you have this sort of question; although parts of it are technical, for the most part it’s pretty readable.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading