-1

I have a method entangled with control structures. It has many ways to exit. Before leaving the method I need to do some final processing. Instead of repeating the same logic before each exit or refactoring that logic in a method and calling it several times it seem handy to leave that in a finally block. Is it really a legitimate use of finally or am I abusing it?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Carlos Nunes
  • 1,929
  • 2
  • 16
  • 20
  • If your Program should e.g. exit (ThreadDeath), your Buisness Logic is executed. I recommend you to catch Exceptions and execute your Buisness logic after that. – dan1st Jul 16 '19 at 15:20
  • 7
    I recommend refactoring the whole thing so that it's not as convoluted as you make it sound. – RealSkeptic Jul 16 '19 at 15:22
  • I don't see any problem with it. Make sure your code in finally doesn't throw any exception other wise you might need a try block in finally too – Deepesh kumar Gupta Jul 16 '19 at 15:22
  • 1
    It depends. If you have that much entanglement in a single control structure then it's likely missing refactorings. – Dave Newton Jul 16 '19 at 15:23
  • Also it tdepends on how mission-critical it is: remember that `finally` is not guaranteed to kick in simply because power outages, people tripping over cords, VM crashes, kill-9, etc. are all real things that can happen. – Mike 'Pomax' Kamermans Jul 16 '19 at 15:49
  • `try { generateEnergy(); } finally { shutdownNuclearReactor(); }`? Uhhhm - no. But it indeed sounds like it should first be tackled with a refactoring. If you provide some code (maybe even sketchy, showing the messed up control flow and how you want to (ab)use `finally`), one can give a more focused answer. – Marco13 Jul 16 '19 at 15:55

1 Answers1

4

finally is there for a reason, to add logic that must be execute before the exiting block

It's a valid choice for a method if you don't want/need to use AOP/AspectJ

Notice you may have to use finally for release resources as Connection

For example you can use it when you must audit/log or do autonomous transaction at the end of the method

As @DaveNewton comment, in some cases there might be a better way of refactoring/separating logic, but you can't ignore that it's a valid usage

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Ori Marko
  • 56,308
  • 23
  • 131
  • 233