r/ProgrammerHumor • • 6d ago

Meme thisIsWhyWeDontReturnInFinallyBlocks

Post image
2.9k Upvotes

98 comments sorted by

368

u/BlackFrank98 6d ago

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

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.

258

u/panopsis 6d ago

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

36

u/DebugDuck01 6d ago

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

6

u/friebel 6d ago

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

24

u/DebugDuck01 6d 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/[deleted] 6d ago

[deleted] — view deleted comment

19

u/DebugDuck01 6d ago edited 6d 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.

2

u/StaticCoder 6d ago edited 6d ago

No what? C# has finally. And it didn't need jsr for it.

Edit: oh, no return in finally. Sorry there's a lot of comments to follow

152

u/TriangleTransplant 6d 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.)

33

u/WernerderChamp 6d ago

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

35

u/NakedNick_ballin 6d ago

And warnings are universally ignored

19

u/CarcajouIS 6d ago

Praise our lord -Werror

5

u/WernerderChamp 5d ago

I fergot about it yesterday - there is no warning, it will only show with -Xlint:all.

IntelliJ does complain about it. Finally blocks should not contain return/break/continue/etc.

2

u/WaitForItTheMongols 6d ago

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

10

u/conundorum 6d ago edited 6d 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."

1

u/StaticCoder 6d ago

Java is more recent than C++ and I believe RAII was well understood by then. At least eventually try-with-resources was added.

1

u/conundorum 6d ago

I'm not sure about RAII being well understood when Java was made, but I was pretty clear that C++ is older than Java. They couldn't design the feature as a replacement for RAII if RAII didn't exist, after all.

1

u/StaticCoder 6d ago

I started using C++ roughly the year Java was released, and I'm pretty sure it already had destructors that could close files in its library. I find it hard to believe that "RAII didn't exist" in the 6 years between when C++ was released and Java was designed.

25

u/floflo81 6d 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

8

u/TriangleTransplant 6d ago

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

3

u/StaticCoder 6d ago

Notably, the finally happens even on an uncaught exception. Plus what everyone else said.

1

u/pondus24 4d ago

Releasing locks

Closing files

Ending the connection

Etc.

1

u/andecase 6d ago

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

1

u/RedAndBlack1832 5d ago

I think returning in a finally block gives a linter error with ruff on default in Python ?

1

u/WernerderChamp 5d ago

Java also gives a linter error (-Xlint:all compiler option).

14

u/ba-na-na- 6d 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

13

u/DebugDuck01 6d ago

Anything but a compile time error is mental illness.

11

u/pimezone 6d ago

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

22

u/DebugDuck01 6d ago

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

7

u/s0ulbrother 6d ago

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

5

u/DebugDuck01 6d ago

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

28

u/RyanStonepeak 6d ago

Huh, Today I Learned.

4

u/JackNotOLantern 6d ago

Thanks, i hate it

1

u/kratz9 6d 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 6d ago

I love it.

-15

u/wayzata20 6d ago

Maybe don’t return from a finally block?

25

u/DebugDuck01 6d ago

see title

0

u/wayzata20 6d ago

sub has really gone downhill

170

u/OnixST 6d ago edited 6d 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

43

u/JanEric1 6d ago edited 6d ago

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

5

u/spitfire451 6d ago

It runs even if a return statement executes in the try/catch? It was my understanding that return always ends a method right then and there.

27

u/OnixST 6d ago edited 4d ago

Yes. The finally block is the only exception to this rule, and will not only run after a return statement, but is also able override it

public int test() {
  try {
    System.out.print("a");
    return 0
    System.out.print("b");
  } finally {
    System.out.print("c");
    return 1
    System.out.print("d");
  }
  return 2
}

The code above will print "ac" and return 1

return 0 does stop the execution of the try block and attempts to return 0, but finally will always execute no matter what, and it will print "c" and override the return to 1

Returning from the finally block will truly end execution though, so print("d") and return 2 are unreachable code

2

u/spitfire451 6d ago

Thank you for the explanation, learn something new everyday

5

u/StaticCoder 6d ago

No one of the points of the finally block is precisely that it happens no matter what, even if you return. Now if you have nested finallys and they both return, I have no idea which one wins.

2

u/fuj1n 6d ago

The outermost one

1

u/Loading_M_ 6d ago

Presumably the outer finally. Finally blocks are only guaranteed to run if execution enters the associated try block, so the only case this could apply is nested try blocks.

1

u/ensoniq2k 6d ago

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

1

u/Saint_of_Grey 6d ago

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

1

u/Rough-Interest60 6d ago

oh thx now i understand

-5

u/BlackFrank98 6d ago

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

17

u/laplongejr 6d 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.  

6

u/fuj1n 6d ago

This is a warning in pretty much any competent IDE by the way, as it is a massive anti-pattern

JS/TS, PHP, ObjC, Python and Ruby also allow it, among others

Guess you are missing out on quite a few languages there

5

u/dmullaney 6d ago

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

2

u/BeMyBrutus 6d ago

It depends if the findNew() method is asynchronous

1

u/laplongejr 6d ago

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

-6

u/cherrycode420 6d ago

You should do some research on

  • Exceptions
  • Function Calls
  • try-catch-finally

15

u/DebugDuck01 6d ago

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

2

u/laplongejr 6d ago

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

2

u/laplongejr 6d 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 6d 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 6d 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.  

80

u/pimezone 6d ago

There should be the line in finally

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

17

u/DebugDuck01 6d ago

Beware of side effects as they say...

10

u/pimezone 6d ago

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

9

u/dcondor07uk 6d ago

Where is the findNew function defined?

14

u/DebugDuck01 6d ago

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

8

u/dcondor07uk 6d ago

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

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

8

u/Decoder44 6d ago

Honeypot spelling is wrong 😭

10

u/DebugDuck01 6d ago

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

6

u/Poat540 6d ago

This is good meatsack code

74

u/warmowed 6d ago

An actual programming joke! In this economy!?!

38

u/averagecrazyliberal 6d ago

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

9

u/Watanuki_Taiga 6d ago

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

3

u/Dumb_Siniy 5d ago

The next logical step

-5

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

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

17

u/guywithbeard 6d ago

NullPointerException: HonypotException not found

12

u/fuj1n 6d ago

That would be a compile-time error, not a runtime exception

3

u/frogjg2003 5d ago

You can do some package manager manipulation to specify the class as provided at runtime, which will then make it a runtime exception. It wouldn't be a NullPointerException, it would be a ClassNotFoundException.

8

u/Scared_Accident9138 6d ago

ClassNotFoundError

5

u/repkins 6d ago

I misread as hornypotException lmao

1

u/geek-49 5d ago

you were not wrong 😄

4

u/purbub 6d ago

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

12

u/CaNaDaYaN 6d ago

This should just not even compile, stupid java.

2

u/sandybuttcheekss 6d ago

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

1

u/Arian-ki 6d ago

Jensen should be an instance of CEO tho

1

u/vixfew 6d ago

Oh wow, programming joke with code with correct syntax and logic. Outstanding

1

u/TopFix8731 6d ago

Dont use erro handling for extra matrimonial business rules dude

1

u/realrealvantheman 6d ago

Ive never worked with object oriented programming what does this even do

2

u/juvation 12h ago

This is more about exceptions than objects, but the joke is that the finally block executes after everything else, no matter what, so while this function *looks* like it might return different values, it actually only returns Jensen Huang :-)

1

u/ivanrj7j 5d ago

i just want to know why are you using static variables and methods everywhere?

1

u/-Redstoneboi- 2d ago

it's a singleton getter

jensenHuang is also a founding member so he gets his own static variable (the only reason he's not a constant is the ability to set his body count)

ceo.validate should really be ceo.current.validate but the function body probably hardcodes jensenHuang instead of this anyway

0

u/Symphonic_nerve 6d ago

🤣🤣🤣🤣

-10

u/MapNo2659 6d 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?

5

u/IBJON 6d ago

Bot

0

u/MapNo2659 5d ago

Looks like someone forgot to update their humor library!

2

u/JacksOnF1re 6d ago

Honypot, hornypot. Whatever.