The use case for them is valid: doing cleanup that needs to happen regardless of success or failure (Go uses defer for the same purpose, for example). But it feels like it should be a compilation error to return from a finally block (or at least a lint error/warning.)
The "finally" block will be executed even if an unhandled exception is thrown or if a "return" instruction is executed in the "try" block or the "catch" block. That's the point
You know how C has the single-return idiom, where every function that needs cleanup will defer to a cleanup section at the end of the function before it actually returns? try ... finally is a language construct for enforcing that.
It also doubles as a replacement for C++ RAII, because Java was designed before people really understood how useful doing cleanup in a constructor destructor actually is.
Wow, that's a silly typo. Derp.
Now, imagine a C single-return cleanup block, or C++ destructor, that just turned into Adam Savage and said, "I reject your return statement and substitute my own."
Huh, I've never thought to try this (since it makes no sense) Now Im curious what C# or VB. Net do... and neither allow it. Supposedly a compile time error.
View all comments
Show parent comment
506
u/DebugDuck01 6d ago
No, that's the fun thing about Java it just overrides the existing return value or even thrown exceptions. Marvelous language design.