<p>Considering this code, can I be <em>absolutely sure</em> that the <code>finally</code> block always executes, no matter what <code>something()</code> is?</p>

<pre><code>try {  
    something();  
    return success;  
}  
catch (Exception e) {   
    return failure;  
}  
finally {  
    System.out.println("I don't know if this will get printed out");
}
</code></pre>

[{'answer_id': 65049, 'author': 'jodonnell', 'author_id': 4223, 'author_profile': 'https://Stackoverflow.com/users/4223', 'pm_score': 13, 'selected': True, 'text': "<p>Yes, <code>finally</code> will be called after the execution of the <code>try</code> or <code>catch</code> code blocks.</p>\n\n<p>The only times <code>finally</code> won't be called are:</p>\n\n<ol>\n<li>If you invoke <code>System.exit()</code></li>\n<li>If you invoke <code>Runtime.getRuntime().halt(exitStatus)</code></li>\n<li>If the JVM crashes first</li>\n<li>If the JVM reaches an infinite loop (or some other non-interruptable, non-terminating statement) in the <code>try</code> or <code>catch</code> block</li>\n<li>If the OS forcibly terminates the JVM process; e.g., <code>kill -9 &lt;pid&gt;</code> on UNIX</li>\n<li>If the host system dies; e.g., power failure, hardware error, OS panic, et cetera</li>\n<li>If the <code>finally</code> block is going to be executed by a daemon thread and all other non-daemon threads exit before <code>finally</code> is called</li>\n</ol>\n"}, {'answer_id': 65056, 'author': 'shyam', 'author_id': 7616, 'author_profile': 'https://Stackoverflow.com/users/7616', 'pm_score': 4, 'selected': False, 'text': '<p>finally is always executed unless there is abnormal program termination (like calling System.exit(0)..). so, your sysout will get printed</p>\n'}, {'answer_id': 65059, 'author': 'Mendelt', 'author_id': 3320, 'author_profile': 'https://Stackoverflow.com/users/3320', 'pm_score': 3, 'selected': False, 'text': "<p>Yes it will get called. That's the whole point of having a finally keyword. If jumping out of the try/catch block could just skip the finally block it was the same as putting the System.out.println outside the try/catch.</p>\n"}, {'answer_id': 65185, 'author': 'Kevin', 'author_id': 1058366, 'author_profile': 'https://Stackoverflow.com/users/1058366', 'pm_score': 9, 'selected': False, 'text': '<p>Example code:</p>\n<pre><code>public static void main(String[] args) {\n    System.out.println(Test.test());\n}\n\npublic static int test() {\n    try {\n        return 0;\n    }\n    finally {\n        System.out.println(&quot;something is printed&quot;);\n    }\n}\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>something is printed. \n0\n</code></pre>\n'}, {'answer_id': 65219, 'author': 'Scott Dorman', 'author_id': 1559, 'author_profile': 'https://Stackoverflow.com/users/1559', 'pm_score': 3, 'selected': False, 'text': "<p>That's actually true in any language...finally will always execute before a return statement, no matter where that return is in the method body. If that wasn't the case, the finally block wouldn't have much meaning.</p>\n"}, {'answer_id': 65282, 'author': 'user9189', 'author_id': 9189, 'author_profile': 'https://Stackoverflow.com/users/9189', 'pm_score': 4, 'selected': False, 'text': '<p>The finally block is always executed unless there is abnormal program termination, either resulting from a JVM crash or from a call to <code>System.exit(0)</code>.</p>\n\n<p>On top of that, any value returned from within the finally block will override the value returned prior to execution of the finally block, so be careful of checking all exit points when using try finally.</p>\n'}, {'answer_id': 65362, 'author': 'MooBob42', 'author_id': 9271, 'author_profile': 'https://Stackoverflow.com/users/9271', 'pm_score': 9, 'selected': False, 'text': "<p>Also, although it's bad practice, if there is a return statement within the finally block, it will trump any other return from the regular block. That is, the following block would return false:</p>\n\n<pre><code>try { return true; } finally { return false; }\n</code></pre>\n\n<p>Same thing with throwing exceptions from the finally block.</p>\n"}, {'answer_id': 65943, 'author': 'James A. N. Stauffer', 'author_id': 6770, 'author_profile': 'https://Stackoverflow.com/users/6770', 'pm_score': 4, 'selected': False, 'text': '<p>Also a return in finally will throw away any exception.  <a href="http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html" rel="noreferrer">http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html</a></p>\n'}, {'answer_id': 65949, 'author': 'Garth Gilmour', 'author_id': 2635682, 'author_profile': 'https://Stackoverflow.com/users/2635682', 'pm_score': 5, 'selected': False, 'text': "<p>A logical way to think about this is:</p>\n\n<ol>\n<li>Code placed in a finally block must be executed <strong>whatever occurs</strong> within the try block</li>\n<li>So if code in the try block tries to return a value or throw an exception the item is placed 'on the shelf' till the finally block can execute</li>\n<li>Because code in the finally block has (by definition) a high priority it can return or throw whatever it likes. In which case anything left 'on the shelf' is discarded.</li>\n<li>The only exception to this is if the VM shuts down completely during the try block e.g. by 'System.exit'</li>\n</ol>\n"}, {'answer_id': 158141, 'author': 'Alex Miller', 'author_id': 7671, 'author_profile': 'https://Stackoverflow.com/users/7671', 'pm_score': 3, 'selected': False, 'text': '<p>In addition to the point about return in finally replacing a return in the try block, the same is true of an exception.  A finally block that throws an exception will replace a return or exception thrown from within the try block.</p>\n'}, {'answer_id': 296053, 'author': 'vibhash', 'author_id': 38266, 'author_profile': 'https://Stackoverflow.com/users/38266', 'pm_score': 7, 'selected': False, 'text': '<p>I tried the above example with slight modification-</p>\n\n<pre><code>public static void main(final String[] args) {\n    System.out.println(test());\n}\n\npublic static int test() {\n    int i = 0;\n    try {\n        i = 2;\n        return i;\n    } finally {\n        i = 12;\n        System.out.println("finally trumps return.");\n    }\n}\n</code></pre>\n\n<p>The above code outputs:</p>\n\n<blockquote>\n  <p>finally trumps return.<br>\n  2</p>\n</blockquote>\n\n<p>This is because when <code>return i;</code> is executed <code>i</code> has a value 2. After this the <code>finally</code> block is executed where 12 is assigned to <code>i</code> and then <code>System.out</code> out is executed.</p>\n\n<p>After executing the <code>finally</code> block the <code>try</code> block returns 2, rather than returning 12, because this return statement is not executed again.</p>\n\n<p>If you will debug this code in Eclipse then you\'ll get a feeling that after executing <code>System.out</code> of <code>finally</code> block the <code>return</code> statement of <code>try</code> block is executed again. But this is not the case. It simply returns the value 2.</p>\n'}, {'answer_id': 2824754, 'author': 'Motti', 'author_id': 3848, 'author_profile': 'https://Stackoverflow.com/users/3848', 'pm_score': 4, 'selected': False, 'text': '<p>Finally is always run that\'s the whole point, just because it appears in the code after the return doesn\'t mean that that\'s how it\'s implemented. The Java runtime has the responsibility to run this code when exiting the <code>try</code> block.</p>\n\n<p>For example if you have the following:</p>\n\n<pre><code>int foo() { \n    try {\n        return 42;\n    }\n    finally {\n        System.out.println("done");\n    }\n}\n</code></pre>\n\n<p>The runtime will generate something like this:</p>\n\n<pre><code>int foo() {\n    int ret = 42;\n    System.out.println("done");\n    return 42;\n}\n</code></pre>\n\n<p>If an uncaught exception is thrown the <code>finally</code> block will run and the exception will continue propagating. </p>\n'}, {'answer_id': 2824758, 'author': 'Jay Riggs', 'author_id': 52249, 'author_profile': 'https://Stackoverflow.com/users/52249', 'pm_score': 3, 'selected': False, 'text': '<p>Because a finally block will always be called unless you call <code>System.exit()</code> (or the thread crashes).</p>\n'}, {'answer_id': 2824759, 'author': 'Chris Cooper', 'author_id': 300807, 'author_profile': 'https://Stackoverflow.com/users/300807', 'pm_score': 6, 'selected': False, 'text': '<p>That is the whole idea of a finally block. It lets you make sure you do cleanups that might otherwise be skipped because you return, among other things, of course.</p>\n\n<p>Finally gets called <strong>regardless of what happens</strong> in the try block (<em>unless</em> you call <code>System.exit(int)</code> or the Java Virtual Machine kicks out for some other reason).</p>\n'}, {'answer_id': 2824762, 'author': 'vodkhang', 'author_id': 227698, 'author_profile': 'https://Stackoverflow.com/users/227698', 'pm_score': 2, 'selected': False, 'text': "<p>Because the final is always be called in whatever cases you have. You don't have exception, it is still called, catch exception, it is still called</p>\n"}, {'answer_id': 2824998, 'author': 'Eyal Schneider', 'author_id': 196211, 'author_profile': 'https://Stackoverflow.com/users/196211', 'pm_score': 7, 'selected': False, 'text': "<p>In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:</p>\n\n<pre><code>public static int getMonthsInYear() {\n    try {\n        return 10;\n    }\n    finally {\n        return 12;\n    }\n}\n</code></pre>\n\n<p>Similarly, the following method does not throw an exception:</p>\n\n<pre><code>public static int getMonthsInYear() {\n    try {\n        throw new RuntimeException();\n    }\n    finally {\n        return 12;\n    }\n}\n</code></pre>\n\n<p>While the following method does throw it:</p>\n\n<pre><code>public static int getMonthsInYear() {\n    try {\n        return 12;          \n    }\n    finally {\n        throw new RuntimeException();\n    }\n}\n</code></pre>\n"}, {'answer_id': 2826472, 'author': 'Gala101', 'author_id': 338082, 'author_profile': 'https://Stackoverflow.com/users/338082', 'pm_score': 2, 'selected': False, 'text': "<p>Consider this in a normal course of execution (i.e without any Exception being thrown): if method is not 'void' then it always explicitly returns something, yet, finally always gets executed</p>\n"}, {'answer_id': 2902505, 'author': 'Wasim', 'author_id': 349636, 'author_profile': 'https://Stackoverflow.com/users/349636', 'pm_score': 3, 'selected': False, 'text': '<p>This is because you assigned the value of i as 12, but did not return the value of i to the function. The correct code is as follows:</p>\n\n<pre><code>public static int test() {\n    int i = 0;\n    try {\n        return i;\n    } finally {\n        i = 12;\n        System.out.println("finally trumps return.");\n        return i;\n    }\n}\n</code></pre>\n'}, {'answer_id': 2902578, 'author': 'polygenelubricants', 'author_id': 276101, 'author_profile': 'https://Stackoverflow.com/users/276101', 'pm_score': 8, 'selected': False, 'text': '<p>Here\'s the official words from the Java Language Specification.</p>\n\n<p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.20.2" rel="noreferrer">14.20.2. Execution of try-finally and try-catch-finally</a></p>\n\n<blockquote>\n  <p><strong>A <code>try</code> statement with a <code>finally</code> block is executed by first executing the <code>try</code> block. Then there is a choice:</strong></p>\n  \n  <ul>\n  <li>If execution of the <code>try</code> block completes normally, [...]</li>\n  <li>If execution of the <code>try</code> block completes abruptly because of a <code>throw</code> of a value <em>V</em>, [...]</li>\n  <li><strong>If execution of the <code>try</code> block completes abruptly for any other reason <em>R</em>, then the <code>finally</code> block is executed. Then there is a choice:</strong>\n  \n  <ul>\n  <li>If the finally block completes normally, then the <code>try</code> statement completes abruptly for reason <em>R</em>. </li>\n  <li>If the <code>finally</code> block completes abruptly for reason <em>S</em>, then the <code>try</code> statement completes abruptly for reason <em>S</em> (<strong>and reason <em>R</em> is discarded</strong>).</li>\n  </ul></li>\n  </ul>\n</blockquote>\n\n<p>The specification for <code>return</code> actually makes this explicit:</p>\n\n<p><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.17" rel="noreferrer">JLS 14.17 The return Statement</a></p>\n\n<blockquote>\n<pre><code>ReturnStatement:\n     return Expression(opt) ;\n</code></pre>\n  \n  <p>A <code>return</code> statement with no <code>Expression</code> <strong>attempts</strong> to transfer control to the invoker of the method or constructor that contains it. </p>\n  \n  <p>A <code>return</code> statement with an <code>Expression</code> <strong>attempts</strong> to transfer control to the invoker of the method that contains it; the value of the <code>Expression</code> becomes the value of the method invocation.</p>\n  \n  <p>The preceding descriptions say "<em><strong>attempts</strong> to transfer control</em>" rather than just "<em>transfers control</em>" because if there are any <code>try</code> statements within the method or constructor whose <code>try</code> blocks contain the <code>return</code> statement, then any <code>finally</code> clauses of those <code>try</code> statements will be executed, in order, innermost to outermost, before control is transferred to the invoker of the method or constructor. Abrupt completion of a <code>finally</code> clause can disrupt the transfer of control initiated by a <code>return</code> statement.</p>\n</blockquote>\n'}, {'answer_id': 7756997, 'author': 'Bhushan', 'author_id': 645226, 'author_profile': 'https://Stackoverflow.com/users/645226', 'pm_score': 3, 'selected': False, 'text': '<p>If an exception is thrown, finally runs. If an exception is not thrown, finally runs. If the exception is caught, finally runs. If the exception is not caught, finally runs.</p>\n\n<p>Only time it does not run is when JVM exits.</p>\n'}, {'answer_id': 10188271, 'author': 'eric2323223', 'author_id': 44512, 'author_profile': 'https://Stackoverflow.com/users/44512', 'pm_score': 2, 'selected': False, 'text': '<p>Try this code, you will understand the <strong>code in finally block is get executed after return statement</strong>.</p>\n\n<pre><code>public class TestTryCatchFinally {\n    static int x = 0;\n\n    public static void main(String[] args){\n        System.out.println(f1() );\n        System.out.println(f2() );\n    }\n\n    public static int f1(){\n        try{\n            x = 1;\n            return x;\n        }finally{\n            x = 2;\n        }\n    }\n\n    public static int f2(){\n        return x;\n    }\n}\n</code></pre>\n'}, {'answer_id': 17634958, 'author': 'Rajendra Jadi', 'author_id': 2287871, 'author_profile': 'https://Stackoverflow.com/users/2287871', 'pm_score': 4, 'selected': False, 'text': '<p>No, not always one exception case is//\nSystem.exit(0);\nbefore the finally block prevents finally to be  executed.</p>\n\n<pre><code>  class A {\n    public static void main(String args[]){\n        DataInputStream cin = new DataInputStream(System.in);\n        try{\n            int i=Integer.parseInt(cin.readLine());\n        }catch(ArithmeticException e){\n        }catch(Exception e){\n           System.exit(0);//Program terminates before executing finally block\n        }finally{\n            System.out.println("Won\'t be executed");\n            System.out.println("No error");\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 18272854, 'author': 'Karthikeyan', 'author_id': 1927543, 'author_profile': 'https://Stackoverflow.com/users/1927543', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, it will. No matter what happens in your try or catch block unless otherwise System.exit() called or JVM crashed. if there is any return statement in the block(s),finally will be executed prior to that return statement.</p>\n'}, {'answer_id': 20363941, 'author': 'WoodenKitty', 'author_id': 2684342, 'author_profile': 'https://Stackoverflow.com/users/2684342', 'pm_score': 7, 'selected': False, 'text': '<p>Here\'s an elaboration of <a href="https://stackoverflow.com/a/65185/2684342">Kevin\'s answer</a>. It\'s important to know that the expression to be returned is evaluated before <code>finally</code>, even if it is returned after.</p>\n<pre><code>public static void main(String[] args) {\n    System.out.println(Test.test());\n}\n\npublic static int printX() {\n    System.out.println(&quot;X&quot;);\n    return 0;\n}\n\npublic static int test() {\n    try {\n        return printX();\n    }\n    finally {\n        System.out.println(&quot;finally trumps return... sort of&quot;);\n        return 42;\n    }\n}\n</code></pre>\n<p>Output:</p>\n<pre class="lang-none prettyprint-override"><code>X\nfinally trumps return... sort of\n42\n</code></pre>\n'}, {'answer_id': 21125379, 'author': 'abhig', 'author_id': 1596606, 'author_profile': 'https://Stackoverflow.com/users/1596606', 'pm_score': 3, 'selected': False, 'text': '<p>Yes It will.\nOnly case it will not is JVM exits or crashes </p>\n'}, {'answer_id': 21824431, 'author': 'Rohit Chugh', 'author_id': 3317784, 'author_profile': 'https://Stackoverflow.com/users/3317784', 'pm_score': 2, 'selected': False, 'text': '<p>Finally block always execute whether exception  handle or not .if any exception occurred before try block then finally block will not execute.</p>\n'}, {'answer_id': 26349456, 'author': 'bikz05', 'author_id': 3149356, 'author_profile': 'https://Stackoverflow.com/users/3149356', 'pm_score': 3, 'selected': False, 'text': '<p>Concisely, in the official Java Documentation (Click <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html" rel="noreferrer">here</a>), it is written that - </p>\n\n<blockquote>\n  <p>If the JVM exits while the try or catch code is being executed, then\n  the finally block may not execute. Likewise, if the thread executing\n  the try or catch code is interrupted or killed, the finally block may\n  not execute even though the application as a whole continues.</p>\n</blockquote>\n'}, {'answer_id': 27249545, 'author': 'Gautam Viradiya', 'author_id': 4315585, 'author_profile': 'https://Stackoverflow.com/users/4315585', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, finally block is always execute. Most of developer use this block the closing the database connection, resultset object, statement object and also uses into the java hibernate to rollback the transaction.</p>\n'}, {'answer_id': 27540550, 'author': 'Utkarsh Bhatt', 'author_id': 3201107, 'author_profile': 'https://Stackoverflow.com/users/3201107', 'pm_score': 3, 'selected': False, 'text': '<p><code>finally</code> will execute and that is for sure.</p>\n\n<p><code>finally</code> will not execute in below cases: </p>\n\n<p>case 1 :</p>\n\n<p>When you are executing <code>System.exit()</code>.</p>\n\n<p>case 2 :</p>\n\n<p>When your JVM / Thread crashes.</p>\n\n<p>case 3 : </p>\n\n<p>When your execution is stopped in between manually.</p>\n'}, {'answer_id': 30213111, 'author': 'milton', 'author_id': 873900, 'author_profile': 'https://Stackoverflow.com/users/873900', 'pm_score': 3, 'selected': False, 'text': '<p>I was very confused with all the answers provided on different forums and decided to finally code and see. The ouput is :</p>\n<p><strong>finally will be executed even if there is return in try and catch block.</strong></p>\n<pre><code>try {  \n  System.out.println(&quot;try&quot;); \n  return;\n  //int  i =5/0;\n  //System.exit(0 ) ;\n} catch (Exception e) {   \n  System.out.println(&quot;catch&quot;);\n  return;\n  //int  i =5/0;\n  //System.exit(0 ) ;\n} finally {  \n   System.out.println(&quot;Print me FINALLY&quot;);\n}\n</code></pre>\n<p><strong>Output</strong></p>\n<blockquote>\n<p>try</p>\n<p>Print me FINALLY</p>\n</blockquote>\n<ol start="2">\n<li>If return is replaced by <code>System.exit(0)</code> in try and catch block in above code and an exception occurs before it,for any reason.</li>\n</ol>\n'}, {'answer_id': 34240980, 'author': 'Anonymous Coward', 'author_id': 956880, 'author_profile': 'https://Stackoverflow.com/users/956880', 'pm_score': 4, 'selected': False, 'text': '<h1>NOT ALWAYS</h1>\n\n<p>The Java Language specification describes how <code>try</code>-<code>catch</code>-<code>finally</code> and <code>try</code>-<code>catch</code> blocks work at <a href="https://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2" rel="nofollow noreferrer">14.20.2</a><br>\nIn no place it specifies that the <code>finally</code> block is always executed.\nBut for all cases in which the <code>try</code>-<code>catch</code>-<code>finally</code> and <code>try</code>-<code>finally</code> blocks complete it does specify that before completion <code>finally</code> must be executed.</p>\n\n<pre><code>try {\n  CODE inside the try block\n}\nfinally {\n  FIN code inside finally block\n}\nNEXT code executed after the try-finally block (may be in a different method).\n</code></pre>\n\n<p>The JLS does not guarantee that <strong>FIN</strong> is executed after <strong>CODE</strong>.\nThe JLS guarantees that if <strong>CODE</strong> and <strong>NEXT</strong> are executed then <strong>FIN</strong> will always be executed after <strong>CODE</strong> and before <strong>NEXT</strong>.</p>\n\n<p>Why doesn\'t the JLS guarantee that the <code>finally</code> block is always executed after the <code>try</code> block? <em>Because it is impossible.</em> It is unlikely but possible that the JVM will be aborted (kill, crash, power off) just after completing the <code>try</code> block but before execution of the <code>finally</code> block. There is nothing the JLS can do to avoid this.</p>\n\n<p>Thus, any software which for their proper behaviour depends on <code>finally</code> blocks always being executed after their <code>try</code> blocks complete are bugged.</p>\n\n<p><code>return</code> instructions in the <code>try</code> block are irrelevant to this issue. If execution reaches code after the <code>try</code>-<code>catch</code>-<code>finally</code> it is guaranteed that the <code>finally</code> block will have been executed before, with or without <code>return</code> instructions inside the <code>try</code> block.</p>\n'}, {'answer_id': 36116269, 'author': 'dkb', 'author_id': 2987755, 'author_profile': 'https://Stackoverflow.com/users/2987755', 'pm_score': 3, 'selected': False, 'text': '<p>I tried this,\nIt is single threaded.</p>\n\n<pre><code>public static void main(String args[]) throws Exception {\n    Object obj = new Object();\n    try {\n        synchronized (obj) {\n            obj.wait();\n            System.out.println("after wait()");\n        }\n    } catch (Exception ignored) {\n    } finally {\n        System.out.println("finally");\n    }\n}\n</code></pre>\n\n<p>The <code>main</code> <code>Thread</code> will be on <code>wait</code> state forever, hence <em><code>finally</code> will never be called</em>,</p>\n\n<p>so console output will not <code>print</code> <code>String</code>: after <code>wait()</code> or <code>finally</code></p>\n\n<p>Agreed with @Stephen C, the above example is one of the 3rd case mention <a href="https://stackoverflow.com/a/65049/2987755">here</a>:</p>\n\n<p>Adding some more such infinite loop possibilities in following code:</p>\n\n<pre><code>// import java.util.concurrent.Semaphore;\n\npublic static void main(String[] args) {\n    try {\n        // Thread.sleep(Long.MAX_VALUE);\n        // Thread.currentThread().join();\n        // new Semaphore(0).acquire();\n        // while (true){}\n        System.out.println("after sleep join semaphore exit infinite while loop");\n    } catch (Exception ignored) {\n    } finally {\n        System.out.println("finally");\n    }\n}\n</code></pre>\n\n<p>Case 2: If the JVM crashes first</p>\n\n<pre><code>import sun.misc.Unsafe;\nimport java.lang.reflect.Field;\n\npublic static void main(String args[]) {\n    try {\n        unsafeMethod();\n        //Runtime.getRuntime().halt(123);\n        System.out.println("After Jvm Crash!");\n    } catch (Exception e) {\n    } finally {\n        System.out.println("finally");\n    }\n}\n\nprivate static void unsafeMethod() throws NoSuchFieldException, IllegalAccessException {\n    Field f = Unsafe.class.getDeclaredField("theUnsafe");\n    f.setAccessible(true);\n    Unsafe unsafe = (Unsafe) f.get(null);\n    unsafe.putAddress(0, 0);\n}\n</code></pre>\n\n<p>Ref: <a href="https://stackoverflow.com/q/65200/2987755">How do you crash a JVM?</a></p>\n\n<p>Case 6: If <code>finally</code> block is going to be executed by daemon <code>Thread</code> and all other non-daemon <code>Threads</code> exit before <code>finally</code> is called.</p>\n\n<pre><code>public static void main(String args[]) {\n    Runnable runnable = new Runnable() {\n        @Override\n        public void run() {\n            try {\n                printThreads("Daemon Thread printing");\n                // just to ensure this thread will live longer than main thread\n                Thread.sleep(10000);\n            } catch (Exception e) {\n            } finally {\n                System.out.println("finally");\n            }\n        }\n    };\n    Thread daemonThread = new Thread(runnable);\n    daemonThread.setDaemon(Boolean.TRUE);\n    daemonThread.setName("My Daemon Thread");\n    daemonThread.start();\n    printThreads("main Thread Printing");\n}\n\nprivate static synchronized void printThreads(String str) {\n    System.out.println(str);\n    int threadCount = 0;\n    Set&lt;Thread&gt; threadSet = Thread.getAllStackTraces().keySet();\n    for (Thread t : threadSet) {\n        if (t.getThreadGroup() == Thread.currentThread().getThreadGroup()) {\n            System.out.println("Thread :" + t + ":" + "state:" + t.getState());\n            ++threadCount;\n        }\n    }\n    System.out.println("Thread count started by Main thread:" + threadCount);\n    System.out.println("-------------------------------------------------");\n}\n</code></pre>\n\n<p>output: This does not print "finally" which implies "Finally block" in "daemon thread" did not execute  </p>\n\n<blockquote>\n<pre><code>main Thread Printing  \nThread :Thread[My Daemon Thread,5,main]:state:BLOCKED  \nThread :Thread[main,5,main]:state:RUNNABLE  \nThread :Thread[Monitor Ctrl-Break,5,main]:state:RUNNABLE   \nThread count started by Main thread:3  \n-------------------------------------------------  \nDaemon Thread printing  \nThread :Thread[My Daemon Thread,5,main]:state:RUNNABLE  \nThread :Thread[Monitor Ctrl-Break,5,main]:state:RUNNABLE  \nThread count started by Main thread:2  \n-------------------------------------------------  \n\nProcess finished with exit code 0\n</code></pre>\n</blockquote>\n'}, {'answer_id': 36926373, 'author': 'HopefullyHelpful', 'author_id': 5191731, 'author_profile': 'https://Stackoverflow.com/users/5191731', 'pm_score': 2, 'selected': False, 'text': '<p><code>finally</code> can also be exited prematurely if an <code>Exception</code> is <code>throw</code>n inside a <em>nested <code>finally</code> block</em>. The compiler will warn you that the <code>finally</code> block does not complete normally or give an error that you have unreachable code. The error for unreachable code will be shown only if the <code>throw</code> is not behind a conditional statement or inside a loop.</p>\n\n<pre><code>try{\n}finally{\n   try{\n   }finally{\n      //if(someCondition) --&gt; no error because of unreachable code\n      throw new RunTimeException();\n   }\n   int a = 5;//unreachable code\n}\n</code></pre>\n'}, {'answer_id': 38187529, 'author': 'dibo', 'author_id': 6547976, 'author_profile': 'https://Stackoverflow.com/users/6547976', 'pm_score': 2, 'selected': False, 'text': '<p>Same with the following code:</p>\n\n<pre><code>static int f() {\n    while (true) {\n        try {\n            return 1;\n        } finally {\n            break;\n        }\n    }\n    return 2;\n}\n</code></pre>\n\n<p>f will return 2!</p>\n'}, {'answer_id': 38930134, 'author': 'Meet Vora', 'author_id': 5373110, 'author_profile': 'https://Stackoverflow.com/users/5373110', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>Answer is simple <strong>YES</strong>.</p>\n</blockquote>\n\n<p><strong>INPUT:</strong></p>\n\n<pre><code>try{\n    int divideByZeroException = 5 / 0;\n} catch (Exception e){\n    System.out.println("catch");\n    return;    // also tried with break; in switch-case, got same output\n} finally {\n    System.out.println("finally");\n}\n</code></pre>\n\n<p><strong>OUTPUT:</strong></p>\n\n<pre><code>catch\nfinally\n</code></pre>\n'}, {'answer_id': 39462828, 'author': 'Akash Manngroliya', 'author_id': 5089473, 'author_profile': 'https://Stackoverflow.com/users/5089473', 'pm_score': 2, 'selected': False, 'text': '<p>Yes it will always called but in one situation it not call when you use System.exit()</p>\n\n<pre><code>try{\n//risky code\n}catch(Exception e){\n//exception handling code\n}\nfinally(){\n//It always execute but before this block if there is any statement like System.exit(0); then this block not execute.\n}\n</code></pre>\n'}, {'answer_id': 44085757, 'author': 'Avinash Pande', 'author_id': 4295595, 'author_profile': 'https://Stackoverflow.com/users/4295595', 'pm_score': 3, 'selected': False, 'text': "<ol>\n<li>Finally  Block always get executed. Unless and until\n<strong>System.exit()</strong> statement exists there (first statement in finally block).</li>\n<li>If <strong>system.exit()</strong> is first statement then finally block won't get executed and control come out of the finally block.\nWhenever System.exit() statement gets in finally block till that statement finally block executed and when System.exit() appears then control force fully come out of the finally block.</li>\n</ol>\n"}, {'answer_id': 44436111, 'author': 'Vikas Suryawanshi', 'author_id': 7504001, 'author_profile': 'https://Stackoverflow.com/users/7504001', 'pm_score': 3, 'selected': False, 'text': "<p>If you don't handle exception, before terminating the program, JVM executes finally block. It will not executed only if normal execution of program will fail mean's termination of program due to these following reasons..</p>\n\n<ol>\n<li><p>By causing a fatal error that causes the process to abort.</p></li>\n<li><p>Termination of program due to memory corrupt.</p></li>\n<li><p>By calling System.exit()</p></li>\n<li><p>If program goes into infinity loop.</p></li>\n</ol>\n"}, {'answer_id': 47198461, 'author': 'Sandip Solanki', 'author_id': 6826372, 'author_profile': 'https://Stackoverflow.com/users/6826372', 'pm_score': 3, 'selected': False, 'text': '<p>The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.</p>\n\n<p>Let me try to answer your question in the easiest possible way.</p>\n\n<p><strong>Rule 1</strong> : The finally block always run\n (Though there are exceptions to it. But let\'s stick to this for sometime.)</p>\n\n<p><strong>Rule 2</strong> : the statements in the finally block run when control leaves a try or a catch block.The transfer of control can occur as a result of normal execution ,of execution of a break , continue, goto or a return statement, or of a propogation of an exception.</p>\n\n<p>In case of a return statement specifically (since its captioned), the control has to leave the calling method , And hence calls the finally block of the corresponding  try-finally structure. The return statement is executed after the finally block.</p>\n\n<p>In case there\'s a return statement in the finally block also, it will definitely override the one pending at the try block , since its clearing the call stack.</p>\n\n<p>You can refer a better explanation here : <a href="http://msdn.microsoft.com/en-us/" rel="noreferrer">http://msdn.microsoft.com/en-us/</a>.... the concept is mostly same in all the high level languages.</p>\n'}, {'answer_id': 47847227, 'author': 'Dávid Horváth', 'author_id': 3948862, 'author_profile': 'https://Stackoverflow.com/users/3948862', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, because <strong>no control statement</strong> can prevent <code>finally</code> from being executed.</p>\n\n<p>Here is a reference example, where all code blocks will be executed:</p>\n\n<pre><code>| x | Current result | Code \n|---|----------------|------ - - -\n|   |                |     \n|   |                | public static int finallyTest() {\n| 3 |                |     int x = 3;\n|   |                |     try {\n|   |                |        try {\n| 4 |                |             x++;\n| 4 | return 4       |             return x;\n|   |                |         } finally {\n| 3 |                |             x--;\n| 3 | throw          |             throw new RuntimeException("Ahh!");\n|   |                |         }\n|   |                |     } catch (RuntimeException e) {\n| 4 | return 4       |         return ++x;\n|   |                |     } finally {\n| 3 |                |         x--;\n|   |                |     }\n|   |                | }\n|   |                |\n|---|----------------|------ - - -\n|   | Result: 4      |\n</code></pre>\n\n<p>In the variant below, <code>return x;</code> will be skipped. Result is still <code>4</code>:</p>\n\n<pre><code>public static int finallyTest() {\n    int x = 3;\n    try {\n        try {\n            x++;\n            if (true) throw new RuntimeException("Ahh!");\n            return x; // skipped\n        } finally {\n            x--;\n        }\n    } catch (RuntimeException e) {\n        return ++x;\n    } finally {\n        x--;\n    }\n}\n</code></pre>\n\n<p>References, of course, track their status. This example returns a reference with <code>value = 4</code>:</p>\n\n<pre><code>static class IntRef { public int value; }\npublic static IntRef finallyTest() {\n    IntRef x = new IntRef();\n    x.value = 3;\n    try {\n        return x;\n    } finally {\n        x.value++; // will be tracked even after return\n    }\n}\n</code></pre>\n'}, {'answer_id': 49614632, 'author': 'Danail Tsvetanov', 'author_id': 5635466, 'author_profile': 'https://Stackoverflow.com/users/5635466', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, it is written <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html" rel="noreferrer">here</a></p>\n\n<blockquote>\n  <p>If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.</p>\n</blockquote>\n'}, {'answer_id': 49752573, 'author': 'Pradeep Kumaresan', 'author_id': 2851699, 'author_profile': 'https://Stackoverflow.com/users/2851699', 'pm_score': 3, 'selected': False, 'text': '<p>Adding to <a href="https://stackoverflow.com/a/296053/4298200">@vibhash\'s answer</a> as no other answer explains what happens in the case of a mutable object like the one below.</p>\n\n<pre><code>public static void main(String[] args) {\n    System.out.println(test().toString());\n}\n\npublic static StringBuffer test() {\n    StringBuffer s = new StringBuffer();\n    try {\n        s.append("sb");\n        return s;\n    } finally {\n        s.append("updated ");\n    }\n}\n</code></pre>\n\n<p>Will output</p>\n\n<blockquote>\n<pre><code>sbupdated \n</code></pre>\n</blockquote>\n'}, {'answer_id': 49850492, 'author': 'Poorna Senani Gamage', 'author_id': 8111997, 'author_profile': 'https://Stackoverflow.com/users/8111997', 'pm_score': 3, 'selected': False, 'text': '<p><code>try</code>- <code>catch</code>- <code>finally</code> are the key words for using exception handling case.<br> \nAs normal explanotory</p>\n\n<pre><code>try {\n     //code statements\n     //exception thrown here\n     //lines not reached if exception thrown\n} catch (Exception e) {\n    //lines reached only when exception is thrown\n} finally {\n    // always executed when the try block is exited\n    //independent of an exception thrown or not\n}\n</code></pre>\n\n<p>The finally block  prevent executing...</p>\n\n<ul>\n<li>When you called <code>System.exit(0);</code></li>\n<li>If JVM exits.</li>\n<li>Errors in the JVM</li>\n</ul>\n'}, {'answer_id': 49951065, 'author': 'aliceangel', 'author_id': 6706261, 'author_profile': 'https://Stackoverflow.com/users/6706261', 'pm_score': 2, 'selected': False, 'text': '<p>finally block is executed always even if you put a return statement in the try block. The finally block will be executed before the return statement.</p>\n'}, {'answer_id': 50096809, 'author': 'sam', 'author_id': 7538821, 'author_profile': 'https://Stackoverflow.com/users/7538821', 'pm_score': 3, 'selected': False, 'text': '<p>Consider the following program:</p>\n\n<pre><code>public class SomeTest {\n\n    private static StringBuilder sb = new StringBuilder();\n\n    public static void main(String args[]) {\n\n        System.out.println(someString());\n        System.out.println("---AGAIN---");\n        System.out.println(someString());\n        System.out.println("---PRINT THE RESULT---");\n        System.out.println(sb.toString());\n    }\n\n    private static String someString() {\n\n        try {\n            sb.append("-abc-");\n            return sb.toString();\n\n        } finally {\n            sb.append("xyz");\n        }\n    }\n}\n</code></pre>\n\n<p>As of Java 1.8.162, the above code block gives the following output:</p>\n\n<pre><code>-abc-\n---AGAIN---\n-abc-xyz-abc-\n---PRINT THE RESULT---\n-abc-xyz-abc-xyz\n</code></pre>\n\n<p>this means that using <code>finally</code> to free up objects is a good practice like the following code:</p>\n\n<pre><code>private static String someString() {\n\n    StringBuilder sb = new StringBuilder();\n\n    try {\n        sb.append("abc");\n        return sb.toString();\n\n    } finally {\n        sb = null; // Just an example, but you can close streams or DB connections this way.\n    }\n}\n</code></pre>\n'}, {'answer_id': 50262581, 'author': 'Rubin Luitel', 'author_id': 6929015, 'author_profile': 'https://Stackoverflow.com/users/6929015', 'pm_score': 2, 'selected': False, 'text': '<p>Finally is always called at the end</p>\n\n<p>when you try, it executes some code, if something happens in try, then catch will catch that exception and you could print some mssg out or throw an error, then finally block is executed.</p>\n\n<p>Finally is normally used when doing cleanups, for instance, if you use a scanner in java, you should probably close the scanner as it leads to other problems such as not being able to open some file</p>\n'}, {'answer_id': 57402744, 'author': 'Mike', 'author_id': 448078, 'author_profile': 'https://Stackoverflow.com/users/448078', 'pm_score': 2, 'selected': False, 'text': '<p>Here are some conditions which can bypass a finally block:</p>\n\n<ol>\n<li>If the JVM exits while the try or catch code is being executed, then the finally block may not execute. More on <a href="http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html" rel="nofollow noreferrer">sun tutorial</a>  </li>\n<li>Normal Shutdown - this occurs either when the last non-daemon thread exits OR when Runtime.exit() (<a href="http://geekexplains.blogspot.com/2008/06/jvm-shutdown-jvm-shutdown-sequence.html" rel="nofollow noreferrer">some good blog</a>). When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned finally blocks are not executed, stacks are not unwound the JVM just exits. Daemon threads should be used sparingly few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for "housekeeping" tasks, such as a background thread that periodically removes expired entries from an in-memory cache (<a href="https://rads.stackoverflow.com/amzn/click/com/0321349601" rel="nofollow noreferrer" rel="nofollow noreferrer">source</a>)</li>\n</ol>\n\n<p>Last non-daemon thread exits example:  </p>\n\n<pre><code>public class TestDaemon {\n    private static Runnable runnable = new Runnable() {\n        @Override\n        public void run() {\n            try {\n                while (true) {\n                    System.out.println("Is alive");\n                    Thread.sleep(10);\n                    // throw new RuntimeException();\n                }\n            } catch (Throwable t) {\n                t.printStackTrace();\n            } finally {\n                System.out.println("This will never be executed.");\n            }\n        }\n    };\n\n    public static void main(String[] args) throws InterruptedException {\n        Thread daemon = new Thread(runnable);\n        daemon.setDaemon(true);\n        daemon.start();\n        Thread.sleep(100);\n        // daemon.stop();\n        System.out.println("Last non-daemon thread exits.");\n    }\n}\n</code></pre>\n\n<p>Output:  </p>\n\n<pre><code>Is alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\nLast non-daemon thread exits.\nIs alive\nIs alive\nIs alive\nIs alive\nIs alive\n</code></pre>\n'}, {'answer_id': 59932063, 'author': 'hellzone', 'author_id': 1379734, 'author_profile': 'https://Stackoverflow.com/users/1379734', 'pm_score': 3, 'selected': False, 'text': "<p><code>finally</code> block is always executed and before returning <code>x</code>'s (calculated) value.</p>\n<pre><code>System.out.println(&quot;x value from foo() = &quot; + foo());\n\n...\n\nint foo() {\n  int x = 2;\n  try {\n    return x++;\n  } finally {\n    System.out.println(&quot;x value in finally = &quot; + x);\n  }\n}\n</code></pre>\n<p>Output:</p>\n<blockquote>\n<p>x value in finally = 3<br />\nx value from foo() = 2</p>\n</blockquote>\n"}, {'answer_id': 60123997, 'author': 'Youngrok Ko', 'author_id': 2862834, 'author_profile': 'https://Stackoverflow.com/users/2862834', 'pm_score': 1, 'selected': False, 'text': '<p>try-with-resoruce example</p>\n\n<pre><code>static class IamAutoCloseable implements AutoCloseable {\n    private final String name;\n    IamAutoCloseable(String name) {\n        this.name = name;\n    }\n    public void close() {\n        System.out.println(name);\n    }\n}\n\n@Test\npublic void withResourceFinally() {\n    try (IamAutoCloseable closeable1 = new IamAutoCloseable("closeable1");\n         IamAutoCloseable closeable2 = new IamAutoCloseable("closeable2")) {\n        System.out.println("try");\n    } finally {\n        System.out.println("finally");\n    }\n}\n</code></pre>\n\n<p>Test output:</p>\n\n<pre><code>try\ncloseable2\ncloseable1\nfinally\n</code></pre>\n'}, {'answer_id': 70623392, 'author': 'kevinarpe', 'author_id': 257299, 'author_profile': 'https://Stackoverflow.com/users/257299', 'pm_score': 0, 'selected': False, 'text': '<p>I am terribly late to answer here, but I am surprised that no one mentioned the Java debugger option to drop a stack frame.  I am a heavy user of this feature in IntelliJ.  (I am <em>sure</em> Eclipse and NetBeans has support for the same feature.)</p>\n<p>If I drop stack frame from a the try or catch block that is followed by a finally block, the IDE will prompt me: &quot;Shall I execute the finally block?&quot;  Obviously, this is an artificial runtime environment -- a debugger!</p>\n<p>To answer your question, I would say you can only guarantee it runs if ignore when a debugger is attached, and (like others said) method <code>something()</code> does not (a) call Java method <code>System.exit(int)</code> or (b) C function <code>exit(int)</code> / <code>abort()</code> via JNI or (c) do something crazy like call <code>kill -9 $PID</code> on itself(!).</p>\n'}, {'answer_id': 70841158, 'author': 'tquadrat', 'author_id': 1554195, 'author_profile': 'https://Stackoverflow.com/users/1554195', 'pm_score': 0, 'selected': False, 'text': '<p>The <a href="https://stackoverflow.com/a/65049/1554195">accepted answer</a> is true in nearly all aspects, but it is still only halve the truth at all (ok, 95% of the truth).</p>\n<p>Assume the following code:</p>\n<pre><code>private final Lock m_Lock = new ReentrantLock();\n…\npublic final SomeObject doSomething( final SomeObject arg )\n{\n  final SomeObject retValue;\n  try\n  {\n    lock.lock();\n    retValue = SomeObject( arg );\n  }\n  finally\n  {\n    out.println( &quot;Entering finally block&quot;);\n    callingAnotherMethod( arg, retValue );\n    lock.unlock();\n  }\n  \n  return retValue;\n}\n…\ntry\n{\n   final var result = doSomething( new SomeObject() );\n}\ncatch( final StackOverflowError e ) { /* Deliberately ignored */ }\n</code></pre>\n<p>Calling the method <code>doSomething()</code> will cause a <code>StackOverflowError</code> nearly immediately.</p>\n<p>And the <code>lock</code> will not be released!</p>\n<p>But how could this happen when the <code>finally</code> block is always executed (with the exceptions already listed in the <a href="https://stackoverflow.com/a/65049/1554195">accepted answer</a>)?</p>\n<p>That is because there is <em>no guarantee</em> made that <em>all</em> statements in the <code>finally</code> block are <em>really</em> executed!</p>\n<p>This would be obvious if there would be a call to <code>System.exit()</code> or a <code>throws</code> statement before the call to <code>lock.unlock()</code>.</p>\n<p>But there is nothing like that in the sample code …</p>\n<p>Aside that the two other method calls in the <code>finally</code> block before the call to <code>lock.unlock()</code> will cause another <code>StackOverflowError</code> …</p>\n<p>And voilà, the lock is not released!</p>\n<p>Although the sample code as such is silly, similar patterns can be found a lot in many kinds of software. All works fine as long as nothing ugly happens in the <code>finally</code> block …</p>\n<p>Funny fact is that it does not work in later versions of Java (meaning that in later versions, the lock was released …). No idea when and why this changed.</p>\n<p>But you still have to make sure that the <code>finally</code> block always terminates normally, otherwise it might not matter if (that) it always get executed …</p>\n'}]
['https://Stackoverflow.com/questions/65035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/885027/']