defer keyword like what we do in Golang should be super useful when it comes to multiple returns in different branches in a function which requires cleanup before each return.
I'm curious about why no one has came up with this idea or just I didn't find one...
- No need to write the same cleanup code multiple times before each return
- Handles branches more flexible than try-catch-finally, which could automatically call the only needed deferred functions on the corresponding return
- Automatically cleanup on errors
Another way of achieving this could be adding destructors to classes like in C++. Using destructors could simulate defer flawlessly: https://stackoverflow.com/questions/48117908/is-the-a-practical-way-to-emulate-go-language-defer-in-c-or-c-destructors, but that should be another topic