r/ProgrammerHumor • • 5h ago

Meme thisIsWhyWeDontReturnInFinallyBlocks

Post image
1.4k Upvotes

69 comments sorted by

187

u/BlackFrank98 5h ago

Doesn't this always return CEO.current() or CEO.findNew() without ever getting to CEO.jensenHuang?

274

u/DebugDuck01 5h ago

No, that's the fun thing about Java it just overrides the existing return value or even thrown exceptions. Marvelous language design.

128

u/panopsis 5h ago

It's not Java specific. Python and JS do it too. Finally blocks in general are just weird.

30

u/DebugDuck01 5h ago

at least C# is sensible and is like: NO...

6

u/friebel 4h ago

But why tho? The word finally implies that do it finally, [implied] no matter what.

16

u/DebugDuck01 4h ago

Because this serves no function but to write non obvious behaviour and dead code, it should just be a compile time error.

0

u/Turbulent_Stick1445 4h ago

It serves to provide a space to clean up after the code in the main block, for example close IO streams, etc. It is absolutely necessary for certain applications, though Java's "try with resources" does cater for the major use case for which it was invented in, IMO, a much cleaner way.

If C# isn't making a point to do finally, then either they found a magical way to make sure resources allocated in the main block get closed, or they screwed the implementation up. That said, Microsoft says they do work the same way as Java's on their Microsoft Learn page "Exception-handling statements - throw and try, catch, finally - C# references":

In a try-finally statement, the finally block runs when control leaves the try block. Control might leave the try block as a result of

  • normal execution,
  • execution of a jump statement (that is, return, break, continue, or goto), or
  • propagation of an exception out of the try block.

I didn't know it, but knowing it now actually makes me understand why finally exists in the first place. It didn't seem that hard to put something after the try {} catch that does the same thing! It executing in the event of an unhandled exception or return makes perfect sense.

10

u/DebugDuck01 3h ago edited 3h ago

Of course a finally block is useful it's returning a value from it that is stupid. C# has finally blocks it just throws a compile error if you pull the highly regarded move of using return within.

73

u/TriangleTransplant 4h ago

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.)

13

u/WernerderChamp 4h ago

According to a quick search, there is a compiler warning. I will give it a try later.

10

u/NakedNick_ballin 2h ago

And warnings are universally ignored

7

u/CarcajouIS 1h ago

Praise our lord -Werror

2

u/WaitForItTheMongols 3h ago

But after the try/catch block, everything after the block already happens regardless of success/failure. What does finally accomplish?

15

u/floflo81 3h ago

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

7

u/conundorum 2h ago edited 2h ago

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."

4

u/TriangleTransplant 3h ago

Imagine re throwing from the catch block. Or returning early from inside the try block. Finally will execute regardless.

1

u/andecase 4h ago

I was going to say as a sys admin. Finally is super important in the powershell that I do.

8

u/pimezone 5h ago

Did you have to write the code in the VS code because the Intellij IDEA wasn't happy?

19

u/DebugDuck01 5h ago

No wrote it in IJ but had to suppress two warnings for it to not scream at me in scary colors.

5

u/s0ulbrother 5h ago

It’s called turn all the warning off. Warnings are for assholes

5

u/DebugDuck01 5h ago

Yeah fuck linters, call me when the compiler throws a fit.

8

u/ba-na-na- 4h ago

Well that’s the point of finally, to always run before returning, so I would expect either compile error, or actually overriding all other branches

11

u/DebugDuck01 4h ago

Anything but a compile time error is mental illness.

25

u/RyanStonepeak 5h ago

Huh, Today I Learned.

4

u/JackNotOLantern 5h ago

Thanks, i hate it

1

u/kratz9 5h ago

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. 

1

u/glenpiercev 4h ago

I love it.

-14

u/wayzata20 5h ago

Maybe don’t return from a finally block?

25

u/DebugDuck01 5h ago

see title

1

u/wayzata20 42m ago

sub has really gone downhill

101

u/OnixST 5h ago edited 5h ago

Finally in java is a block that will always run, regardless of what happens within the try/catch blocks

It's meant for closing OS resources and things like that, and is the only case where you can run code after a return instruction

If you put a return inside a finally block, it will always run, meaning it will override the returns inside the try/catch blocks

In the pictured code, if an exception is thrown, CEO.findNew() will run and will apply side effects if there are any, but the function will still always return CEO.jensenHuang

It's a really weird quirk of java, and i have no clue why they don't simply throw a compiler error when you try to return on a finally block to prevent this very unexpected behavior

26

u/JanEric1 5h ago edited 5h ago

Same applies in Python. They only just made it warning two versions ago https://peps.python.org/pep-0765/

3

u/BlackFrank98 5h ago

Thank you for giving me one more reason not to use Java ever again unless I'm under duress...

12

u/laplongejr 4h ago

In 10 years I never saw a return in a finally outside of knowledge exams. It's one of the few things I would consider an immediate refusal on the code review.  

1

u/ensoniq2k 2h ago

Same for Delphi if anyone cares. But Delphi doesn't do return the same way other languages do.

1

u/Saint_of_Grey 1h ago

Sooo... Don't put Goto Skynet.BeginApocalypse() in a finally block?

5

u/dmullaney 5h ago

OP knows about some other exception the rest of us haven't found out yet

2

u/BeMyBrutus 5h ago

It depends if the findNew() method is asynchronous

1

u/laplongejr 4h ago

It will attempt to return one of both, yes. But before that, finally will run and overwrite the return value.  

-3

u/cherrycode420 5h ago

You should do some research on

  • Exceptions
  • Function Calls
  • try-catch-finally

11

u/DebugDuck01 5h ago

I mean sane languages like C# just don't allow this because... like why would you?

2

u/laplongejr 2h ago

Because of retrocompatibility!   (But seriously WHAT usecase is there for THAT? We're not javascript)  

1

u/laplongejr 4h ago

I know about return-in-finally but only from exams. It's absolutely not something you should notice with basic research  

1

u/conundorum 2h ago

Basic research tells you that finally is guaranteed to run before the function actually returns. That should be enough to tell you that a return statement in the finally block is guaranteed to run, too.

That's like saying that "if being a branch statement is absolutely not something you should notice with basic research".

1

u/laplongejr 2h ago

Wouldn't your research tell you that the previous return also defines the return value of a function? It's the unstoppable force vs the immovable object.  

I would be very surprised if any Java dev could tell with 100% certainty the return value (or exception) of that function without trying it out themselves.  

48

u/pimezone 5h ago

There should be the line in finally

trump.println("We have to reinstate Jensen Huang as Nvidia CEO") ;

9

u/DebugDuck01 5h ago

Beware of side effects as they say...

6

u/pimezone 5h ago

Did you mean the stock market manipulation sort of side effects?

6

u/dcondor07uk 5h ago

Where is the findNew function defined?

10

u/DebugDuck01 5h ago

My man asking the real questions. In this abomination CEO is an enum and validate() and findNew() are static methods within that enum.

5

u/dcondor07uk 5h ago

public CEO getCurrentCeo() {
return CEO.jensenHuang;
}

Here, simplified it for anyone interested, but gotta make sure no shenanigans going on in findNew function

13

u/warmowed 2h ago

An actual programming joke! In this economy!?!

8

u/averagecrazyliberal 3h ago

This is exactly what I want to see in this sub. No more is_even() please for the love of god.

1

u/Watanuki_Taiga 1h ago

def is_even(*args, **kwargs): return CEO.JENSEN_HUANG

-2

u/conundorum 2h ago
bool isEven(int num) { return !isOdd(num); }

bool isOdd(int num) { return !isEven(num); }

13

u/guywithbeard 5h ago

NullPointerException: HonypotException not found

5

u/Scared_Accident9138 4h ago

ClassNotFoundError

1

u/repkins 4h ago

I misread as hornypotException lmao

2

u/Decoder44 3h ago

Honeypot spelling is wrong 😭

4

u/DebugDuck01 2h ago

Typos are like chinese spies, we don't talk about them.

2

u/Poat540 1h ago

This is good meatsack code

4

u/purbub 5h ago

Static method and properties? Daring today aren’t we?

10

u/CaNaDaYaN 5h ago

This should just not even compile, stupid java.

1

u/sandybuttcheekss 3h ago

Does find new just return Jensen Huang and have a to-do to update it later?

1

u/Arian-ki 1h ago

Jensen should be an instance of CEO tho

0

u/Symphonic_nerve 5h ago

🤣🤣🤣🤣

-7

u/MapNo2659 5h ago

Haha, this reminds me of the time I accidentally put a return statement in a finally block during a late-night coding session. Debugging that was a nightmare! Anyone else have a similar horror story?

4

u/IBJON 3h ago

Bot

1

u/JacksOnF1re 1h ago

Honypot, hornypot. Whatever.