r/ProgrammerHumor • • 3d ago

Meme thisIsWhyWeDontReturnInFinallyBlocks

Post image
2.7k Upvotes

96 comments sorted by

340

u/BlackFrank98 3d ago

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

476

u/DebugDuck01 3d ago

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

234

u/panopsis 3d ago

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

35

u/DebugDuck01 3d ago

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

6

u/friebel 3d ago

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

23

u/DebugDuck01 3d 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] 3d ago

[deleted] — view deleted comment

19

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

134

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

30

u/WernerderChamp 3d ago

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

31

u/NakedNick_ballin 3d ago

And warnings are universally ignored

17

u/CarcajouIS 3d ago

Praise our lord -Werror

5

u/WernerderChamp 2d 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 3d ago

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

10

u/conundorum 3d ago edited 3d 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 3d 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 3d 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 3d 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 3d 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 3d ago

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

3

u/StaticCoder 3d ago

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

1

u/pondus24 1d ago

Releasing locks

Closing files

Ending the connection

Etc.

1

u/andecase 3d ago

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

1

u/RedAndBlack1832 2d ago

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

1

u/WernerderChamp 2d ago

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

13

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

Anything but a compile time error is mental illness.

11

u/pimezone 3d ago

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

22

u/DebugDuck01 3d 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 3d ago

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

5

u/DebugDuck01 3d ago

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

28

u/RyanStonepeak 3d ago

Huh, Today I Learned.

4

u/JackNotOLantern 3d ago

Thanks, i hate it

1

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

I love it.

-15

u/wayzata20 3d ago

Maybe don’t return from a finally block?

25

u/DebugDuck01 3d ago

see title

0

u/wayzata20 3d ago

sub has really gone downhill

160

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

42

u/JanEric1 3d ago edited 3d ago

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

4

u/spitfire451 3d 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.

25

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

Thank you for the explanation, learn something new everyday

5

u/StaticCoder 3d 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 3d ago

The outermost one

1

u/Loading_M_ 3d 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 3d ago

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

1

u/Saint_of_Grey 3d ago

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

1

u/Rough-Interest60 3d ago

oh thx now i understand

-5

u/BlackFrank98 3d ago

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

17

u/laplongejr 3d 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 3d 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 3d ago

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

2

u/BeMyBrutus 3d ago

It depends if the findNew() method is asynchronous

1

u/laplongejr 3d ago

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

-6

u/cherrycode420 3d ago

You should do some research on

  • Exceptions
  • Function Calls
  • try-catch-finally

15

u/DebugDuck01 3d ago

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

2

u/laplongejr 3d ago

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

2

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

71

u/pimezone 3d ago

There should be the line in finally

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

16

u/DebugDuck01 3d ago

Beware of side effects as they say...

10

u/pimezone 3d ago

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

9

u/dcondor07uk 3d ago

Where is the findNew function defined?

14

u/DebugDuck01 3d 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 3d 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 3d ago

Honeypot spelling is wrong 😭

10

u/DebugDuck01 3d ago

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

6

u/Poat540 3d ago

This is good meatsack code

66

u/warmowed 3d ago

An actual programming joke! In this economy!?!

33

u/averagecrazyliberal 3d ago

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

7

u/Watanuki_Taiga 3d ago

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

3

u/Dumb_Siniy 2d ago

The next logical step

-5

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

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

17

u/guywithbeard 3d ago

NullPointerException: HonypotException not found

12

u/fuj1n 3d ago

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

3

u/frogjg2003 2d 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 3d ago

ClassNotFoundError

5

u/repkins 3d ago

I misread as hornypotException lmao

1

u/geek-49 2d ago

you were not wrong 😄

4

u/purbub 3d ago

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

12

u/CaNaDaYaN 3d ago

This should just not even compile, stupid java.

2

u/sandybuttcheekss 3d ago

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

1

u/Arian-ki 3d ago

Jensen should be an instance of CEO tho

1

u/vixfew 3d ago

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

1

u/TopFix8731 3d ago

Dont use erro handling for extra matrimonial business rules dude

1

u/realrealvantheman 3d ago

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

1

u/ivanrj7j 2d ago

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

0

u/Symphonic_nerve 3d ago

🤣🤣🤣🤣

-10

u/MapNo2659 3d 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 3d ago

Bot

0

u/MapNo2659 2d ago

Looks like someone forgot to update their humor library!

2

u/JacksOnF1re 3d ago

Honypot, hornypot. Whatever.