{"id":346,"date":"2025-07-01T11:45:54","date_gmt":"2025-07-01T11:45:54","guid":{"rendered":"https:\/\/thetestdata.com\/blog\/?p=346"},"modified":"2025-07-16T10:08:10","modified_gmt":"2025-07-16T10:08:10","slug":"why-do-we-use-finally-and-how-it-differs-from-the-final-keyword","status":"publish","type":"post","link":"https:\/\/thetestdata.com\/blog\/why-do-we-use-finally-and-how-it-differs-from-the-final-keyword\/","title":{"rendered":"Why do we use finally and how it differs from the final keyword?"},"content":{"rendered":"\n<p><strong>\u2705 <code>finally<\/code> Keyword: Purpose &amp; Usage<\/strong><\/p>\n\n\n\n<p>The <code>finally<\/code> block in Java is used with <strong>exception handling<\/strong> (<code>try-catch<\/code>) to define a block of code that <strong>always executes<\/strong>, regardless of whether an exception is thrown or caught.<\/p>\n\n\n\n<p><strong>\ud83d\udca1 Purpose:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Ensures that <strong>cleanup code<\/strong> (like closing resources, files, database connections) always runs\u2014even if an exception occurs.<\/li>\n<\/ul>\n\n\n\n<p>\ud83d\udd27 Syntax:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>try {\n    \/\/ Code that may throw exception\n} catch (ExceptionType e) {\n    \/\/ Exception handling\n} finally {\n    \/\/ Cleanup code that always executes\n}<\/code><\/pre>\n\n\n\n<p>\ud83d\udccc <strong>Example<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>FileInputStream file = null;\ntry {\n    file = new FileInputStream(\"data.txt\");\n    \/\/ Read from file\n} catch (IOException e) {\n    System.out.println(\"File error!\");\n} finally {\n    if (file != null) {\n        file.close(); \/\/ Always executed, even if exception is thrown\n    }\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>\u2705 <code>final<\/code> Keyword: Purpose &amp; Usage<\/strong><\/p>\n\n\n\n<p>The <code>final<\/code> keyword is a <strong>non-access modifier<\/strong> used to declare constants, prevent method overriding, or prevent class inheritance.<\/p>\n\n\n\n<p><strong>\ud83d\udd0d Use Cases:<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Final Variable<\/strong>: Value cannot be changed after assignment<\/li>\n\n\n\n<li><strong>Final Method<\/strong>: Cannot be overridden by subclasses<\/li>\n\n\n\n<li><strong>Final Class<\/strong>: Cannot be subclassed<\/li>\n<\/ol>\n\n\n\n<p><strong>\ud83e\udde0 Key Differences: <code>finally<\/code> vs <code>final<\/code><\/strong><\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th>Feature<\/th><th><code>finally<\/code><\/th><th><code>final<\/code><\/th><\/tr><\/thead><tbody><tr><td><strong>Category<\/strong><\/td><td>Exception handling keyword<\/td><td>Non-access modifier<\/td><\/tr><tr><td><strong>Primary Use<\/strong><\/td><td>Ensures execution of cleanup code<\/td><td>Prevents changes (immutability, inheritance, overriding)<\/td><\/tr><tr><td><strong>Context<\/strong><\/td><td>Used with <code>try-catch<\/code> blocks<\/td><td>Used with variables, methods, or classes<\/td><\/tr><tr><td><strong>Execution<\/strong><\/td><td>Always executes (except for <code>System.exit<\/code>)<\/td><td>Not a block, but a modifier<\/td><\/tr><tr><td><strong>Related To<\/strong><\/td><td>Resource management<\/td><td>Code safety, object immutability<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p><strong>\ud83e\udde0 Bonus: Common Interview Question &amp; Answer<\/strong><\/p>\n\n\n\n<p><strong>Q:<\/strong> Can a <code>finally<\/code> block override a <code>return<\/code> statement in a <code>try<\/code> block?<\/p>\n\n\n\n<p><strong>A:<\/strong> Yes, the <code>finally<\/code> block is always executed after the <code>try<\/code>, even if the <code>try<\/code> block has a <code>return<\/code>. However, if the <code>finally<\/code> also has a return, <strong>it overrides<\/strong> the <code>try<\/code>&#8216;s return.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public int test() {\n    try {\n        return 1;\n    } finally {\n        return 2;  \/\/ This will be returned\n    }\n}<\/code><\/pre>\n\n\n\n<p>\ud83d\udff0 <strong>Output: 2<\/strong><\/p>\n\n\n\n<p>\ud83c\udfc1 Final Takeaways<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>finally<\/code> is about <strong>ensuring execution<\/strong> in exception handling.<\/li>\n\n\n\n<li><code>final<\/code> is about <strong>preventing modification<\/strong>, ensuring immutability or inheritance rules.<\/li>\n\n\n\n<li>Though they sound similar, they are used in <strong>completely different contexts<\/strong>.<\/li>\n\n\n\n<li>Knowing where and when to use each is critical for writing <strong>robust<\/strong>, <strong>secure<\/strong>, and <strong>clean<\/strong> Java code.<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Learn the difference between finally and final in Java. Understand how finally ensures cleanup after exceptions and final secures immutability in code.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"site-container-style":"default","site-container-layout":"default","site-sidebar-layout":"default","disable-article-header":"default","disable-site-header":"default","disable-site-footer":"default","disable-content-area-spacing":"default","footnotes":""},"categories":[17],"tags":[],"class_list":["post-346","post","type-post","status-publish","format-standard","hentry","category-java-interview-questions"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/346","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/comments?post=346"}],"version-history":[{"count":2,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/346\/revisions"}],"predecessor-version":[{"id":419,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/posts\/346\/revisions\/419"}],"wp:attachment":[{"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/media?parent=346"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/categories?post=346"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thetestdata.com\/blog\/wp-json\/wp\/v2\/tags?post=346"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}