{"id":3168,"date":"2017-04-01T15:28:07","date_gmt":"2017-04-01T09:58:07","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=3168"},"modified":"2017-04-01T15:28:07","modified_gmt":"2017-04-01T09:58:07","slug":"finally-always-execute-java","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/finally-always-execute-java\/","title":{"rendered":"JAVA &#8211; Does finally always execute in Java"},"content":{"rendered":"<h4 id=\"java-finally-block\"><span style=\"color: #ff6600;\"><b>Java finally block<\/b><\/span><\/h4>\n<ul>\n<li>Java finally block is a block that is used to execute important code such as closing connection, stream etc.<\/li>\n<li>Java finally block is always executed whether exception is handled or not.<\/li>\n<li>Java finally block follows try or catch block.<\/li>\n<li>Finally block in java can be used to put &#8220;cleanup&#8221; code such as closing a file, closing connection etc.<\/li>\n<li>For each try block there can be zero or more catch blocks, but only one finally block.<\/li>\n<\/ul>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter wp-image-3170 size-full\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/03\/Pn.png\" alt=\"\" width=\"467\" height=\"557\" \/><\/p>\n<h4 id=\"note\"><span style=\"color: #808000;\"><b>NOTE: <\/b><\/span><\/h4>\n<ul>\n<li>If you don&#8217;t handle exception, before terminating the program, JVM executes finally block(if any).<\/li>\n<li>The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">public static void main(String[] args) <br\/>{<br\/>    System.out.println(Test.test());<br\/>}<br\/><br\/>public static int test() <br\/>{<br\/>    try <br\/>{<br\/>        return 0;<br\/> }<br\/>    finally <br\/>{<br\/>        System.out.println(&quot;finally trumps return.&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"output\"><span style=\"color: #800080;\"><b>Output:<\/b><\/span><\/h4>\n<p><b>finally trumps return. <\/b><\/p>\n<p><b>0<\/b><\/p>\n<h4 id=\"code-that-shows-finally-runs-after-return\"><span style=\"color: #808000;\"><b>Code that shows finally runs after return<\/b><\/span><\/h4>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">class SomeClass<br\/>{<br\/>    public static void main(String args[]) <br\/>    { <br\/>        \/\/ call the proveIt method and print the return value<br\/>    \tSystem.out.println(SomeClass.proveIt()); <br\/>    }<br\/><br\/>    public static int proveIt()<br\/>    {<br\/>    \ttry <br\/>{  <br\/>            \treturn 1;  <br\/>}  <br\/>    \tfinally <br\/>{  <br\/>    \t    System.out.println(&quot;finally block is run <br\/>            before method returns.&quot;);<br\/>}<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<h4 id=\"output-2\"><span style=\"color: #ff6600;\"><b>Output:<\/b><\/span><\/h4>\n<p><b>finally block is run before method returns.<\/b><\/p>\n<p><b>1<\/b><\/p>\n<ul>\n<li>From the output, observe that the finally block is executed before control is returned to the <b>\u201c<\/b><b>System.out.println<\/b><b>(<\/b><b>SomeClass.proveIt<\/b><b>());\u201d <\/b>statement \u2013 which is why the \u201c1\u201d is output after the \u201cfinally block is run before method returns.\u201d text<\/li>\n<\/ul>\n<h4 id=\"unique-situations-when-finally-will-not-run-after-return\"><span style=\"color: #800080;\"><b>Unique situations when finally will not run after return<\/b><\/span><\/h4>\n<p>The finally block will not be called after return in unique scenarios:<\/p>\n<ul>\n<li>if System.exit() is called first,<\/li>\n<li>if the JVM crashes.<\/li>\n<li>if there is an infinite loop in the try block<\/li>\n<li>if the power turns off<\/li>\n<\/ul>\n<h4 id=\"return-statement-in-both-the-finally-block-and-the-try-block\"><span style=\"color: #808000;\"><b>return statement in both the finally block and the try block<\/b><\/span><\/h4>\n<ul>\n<li>If we have a return statement in both the finally block and the try block<b>,<\/b> then anything that is returned in the finally block will actually override any exception or returned value that is inside the try\/catch block.<\/li>\n<li>Here is an example,<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">public static int getANumber()<br\/>{<br\/>    try<br\/>{<br\/>        return 7;<br\/>    } <br\/>finally<br\/> {<br\/>        return 43;<br\/>    }<br\/>}\t<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<ul>\n<li>The code above will actually return the \u201c43\u201d instead of the \u201c7\u201d, because the return value in the finally block (\u201c43\u201d) will override the return value in the try block (\u201c7\u201d).<\/li>\n<li>if the <b>finally block returns a value<\/b>, it will override any exception thrown in the try\/catch block. Here is an example:<\/li>\n<\/ul>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">java code<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">public static int getANumber()<br\/>{<br\/>    try<br\/>{<br\/>        throw new NoSuchFieldException();<br\/>    } <br\/>finally <br\/>{<br\/>        return 43;<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<ul>\n<li>Running the method above will return a \u201c43\u201d and the exception in the try block will not be thrown.<\/li>\n<li>So a return statement inside the finally block,should be avoided<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p> Does finally always execute in Java &#8211; Java finally block is a block that is used to execute important code such as closing connection, stream etc<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2139],"tags":[5877,5871,5891,5881,5872,5875,5892,5884,5873,5886,5888,5885,5883,5870,5889,5887,5879,5890,5878,5880,5874,5882,5876],"class_list":["post-3168","post","type-post","status-publish","format-standard","hentry","category-java","tag-catch-and-finally-java","tag-does-return-happen-after-finally","tag-does-finally-always-execute-in-java-md","tag-eclipse-suggested-fix-for-warning-finally-block-does-not-complete-normally","tag-how-can-i-break-from-a-trycatch-block-without-throwing-an-exception-in-java","tag-is-needed-return-value-or-not","tag-java-finally-block","tag-java-return-in-finally","tag-java-exceptions-always-reach-finally","tag-return-in-catch-block-java","tag-return-in-finally-block-c","tag-return-in-try-block-java","tag-return-statement-in-try-catch-and-finally-block-in-java","tag-returning-from-a-finally-block-in-java","tag-try-catch-finally-java-example","tag-try-catch-finally-return-c","tag-try-catch-finally-with-return-after-it","tag-try-finally-clauses-defined-and-demonstrated","tag-trycatch-block-return-with-finally-clause-in-java","tag-understanding-try-catch-finally-with-return-and-value-that-it-returns","tag-what-are-the-circumstances-under-which-a-finally-block-will-not-execute","tag-will-finally-execute-after-return-c","tag-working-with-try"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/3168","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=3168"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/3168\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=3168"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=3168"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=3168"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}