Search code examples
javadrybusiness-logicfinally

Is it legitimate to have business logic inside a finally block?


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?


Solution

  • 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