<p>I was surprised recently to find that it's possible to have a return statement in a finally block in Java.</p>

<p>It seems like lots of people think it's a bad thing to do as described in '<a href="https://web.archive.org/web/20070922061412/http://weblogs.java.net/blog/staufferjames/archive/2007/06/_dont_return_in.html" rel="noreferrer">Don't return in a finally clause</a>'. Scratching a little deeper, I also found '<a href="https://web.archive.org/web/20190528011825/http://www.cs.arizona.edu/projects/sumatra/hallofshame/" rel="noreferrer">Java's return doesn't always</a>' which shows some pretty horrible examples of other types of flow control in finally blocks.</p>

<p>So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?</p>

[{'answer_id': 48096, 'author': 'Jason Cohen', 'author_id': 4926, 'author_profile': 'https://Stackoverflow.com/users/4926', 'pm_score': 8, 'selected': True, 'text': '<p>The examples you provided are reason enough to <i>not</i> use flow-control from finally.</p>\n\n<p>Even if there\'s a contrived example where it\'s "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties.  That poor developer might even be you....</p>\n'}, {'answer_id': 48106, 'author': 'Ian', 'author_id': 4396, 'author_profile': 'https://Stackoverflow.com/users/4396', 'pm_score': 4, 'selected': False, 'text': '<p>Adding control structures and returns to finally{} blocks are just another example of "just because you can" abuses which are scattered throughout virtually all development languages.  Jason was right in suggesting it could easily become a maintenance nightmare - the arguments against early returns from functions apply more-so to this case of "late returns".</p>\n\n<p>Finally blocks exist for one purpose, to allow you to completely tidy up after yourself, no matter what happened in all the preceeding code. Principally this is closing / releasing file pointers, database connections etc., though I could see it being stretched to say adding in bespoke auditing.</p>\n\n<p>Anything that affects the return of the function should lie in the try{} block.  Even if you had a method whereby you checked an external state, did a time consuming operation, then checked that state again in case it became invalid, you would still want the second check inside the try{} - if it sat inside finally{} and the long operation failed, you would then be checking that state a second time needlessly.</p>\n'}, {'answer_id': 48444, 'author': 'Tom Hawtin - tackline', 'author_id': 4725, 'author_profile': 'https://Stackoverflow.com/users/4725', 'pm_score': 5, 'selected': False, 'text': '<p>javac will warn of return in finally if you use the -Xlint:finally. Originally javac emitted no warnings - if something is wrong with the code, it should fail to compile. Unfortunately backwards compatibility means that unanticipated ingenious foolishness cannot be prohibited.</p>\n\n<p>Exceptions can be thrown from finally blocks, but in that case the exhibited behaviour is almost certainly what you want.</p>\n'}, {'answer_id': 48740, 'author': 'John Meagher', 'author_id': 3535, 'author_profile': 'https://Stackoverflow.com/users/3535', 'pm_score': 7, 'selected': False, 'text': "<p>I had a REALLY hard time to track down a bug years ago that was caused by this. The code was something like:</p>\n\n<pre><code>Object problemMethod() {\n    Object rtn = null;\n    try {\n        rtn = somethingThatThrewAnException();\n    }\n    finally {\n        doSomeCleanup();\n        return rtn;\n    }\n}\n</code></pre>\n\n<p>What happened is that the exception was thrown down in some other code. It was being caught and logged and rethrown within the <code>somethingThatThrewAnException()</code> method. But the exception wasn't being propagated up past <code>problemMethod()</code>. After a LONG time of looking at this we finally tracked it down to the return method. The return method in the finally block was basically stopping the exception that happened in the try block from propagating up even though it wasn't caught.</p>\n\n<p>Like others have said, while it is legal to return from a finally block according to the Java spec, it is a BAD thing and shouldn't be done.</p>\n"}, {'answer_id': 5196685, 'author': 'Prof. Ondino', 'author_id': 645117, 'author_profile': 'https://Stackoverflow.com/users/645117', 'pm_score': 3, 'selected': False, 'text': '<h2>A simple Groovy Test:</h2>\n\n<pre><code>public class Instance {\n\n  List&lt;String&gt; runningThreads = new ArrayList&lt;String&gt;()\n\n  void test(boolean returnInFinally) {\n\n    println "\\ntest(returnInFinally: $returnInFinally)"\n    println "--------------------------------------------------------------------------"\n    println "before execute"\n    String result = execute(returnInFinally, false)\n    println "after execute -&gt; result: " + result\n    println "--------------------------------------------------------------------------"\n\n    println "before execute"\n    try {\n      result = execute(returnInFinally, true)\n      println "after execute -&gt; result: " + result\n    } catch (Exception ex) {\n      println "execute threw exception: " + ex.getMessage()\n    }  \n    println "--------------------------------------------------------------------------\\n"\n\n  }\n\n  String execute(boolean returnInFinally, boolean throwError) {\n      String thread = Thread.currentThread().getName()\n      println "...execute(returnInFinally: $returnInFinally, throwError: $throwError) - thread: $thread"\n      runningThreads.add(thread)\n      try {\n        if (throwError) {\n          println "...error in execute, throw exception"\n          throw new Exception("as you liked :-)")\n        }\n        println "...return \'OK\' from execute"\n        return "OK"\n      } finally {\n        println "...pass finally block"\n        if (returnInFinally) return "return value from FINALLY ^^"\n        // runningThreads.remove(thread)\n      }\n  }\n}\n\nInstance instance = new Instance()\ninstance.test(false)\ninstance.test(true)\n</code></pre>\n\n<h2>Output:</h2>\n\n<pre><code>test(returnInFinally: false)\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: false, throwError: false) - thread: Thread-116\n...return \'OK\' from execute\n...pass finally block\nafter execute -&gt; result: OK\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: false, throwError: true) - thread: Thread-116\n...error in execute, throw exception\n...pass finally block\nexecute threw exception: as you liked :-)\n-----------------------------------------------------------------------------\n\n\ntest(returnInFinally: true)\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: true, throwError: false) - thread: Thread-116\n...return \'OK\' from execute\n...pass finally block\nafter execute -&gt; result: return value from FINALLY ^^\n-----------------------------------------------------------------------------\nbefore execute\n...execute(returnInFinally: true, throwError: true) - thread: Thread-116\n...error in execute, throw exception\n...pass finally block\nafter execute -&gt; result: return value from FINALLY ^^\n-----------------------------------------------------------------------------\n</code></pre>\n\n<h2>Question:</h2>\n\n<p>One interesting point for me was to see how Groovy deals with implicit returns. In Groovy it is possible to "return" from a method simply leaving a value at the end (without return). What do you think happens, if you uncomment the <em>runningThreads.remove(..)</em> line in the finally statement - will this overwrite the regular return value ("OK") and cover the exception?!</p>\n'}, {'answer_id': 60124650, 'author': 'Ankur Lathi', 'author_id': 2099208, 'author_profile': 'https://Stackoverflow.com/users/2099208', 'pm_score': 2, 'selected': False, 'text': '<p>Returning from inside a <code>finally</code> block will cause <code>exceptions</code> to be lost.</p>\n\n<p><strong>A return statement inside a finally block will cause any exception that might be thrown in the try or catch block to be discarded.</strong> </p>\n\n<p>According to the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2" rel="nofollow noreferrer"><strong>Java Language Specification:</strong></a></p>\n\n<blockquote>\n  <p>If execution of the try block completes abruptly for any other reason\n  R, then the finally block is executed, and then there is a choice:</p>\n\n<pre><code>   If the finally block completes normally, then the try statement\n   completes  abruptly for reason R.\n\n   If the finally block completes abruptly for reason S, then the try\n   statement  completes abruptly for reason S (and reason R is\n   discarded).\n</code></pre>\n</blockquote>\n\n<p><em>Note: As per <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.17" rel="nofollow noreferrer">JLS 14.17</a> - a return statement always completes abruptly.</em></p>\n'}]
['https://Stackoverflow.com/questions/48088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/797/']