Java Myth Busted: Finally Block Not Always Executed

🚨 Java Myth Buster: “Finally block always executes” — Really? 🤔 Most developers confidently say: 👉 “Yes, finally always runs!” ❌ Let’s break that myth with a real example 👇 --- 💻 Code Example: public class Test { public static void main(String[] args) { try { System.out.println("Inside try"); System.exit(1); } finally { System.out.println("Inside finally"); } } } --- 📌 Output: Inside try 😳 Wait… where is the "finally" block? --- 💡 Explanation (Simple & Clear): When "System.exit(1)" is executed: - 🚫 JVM shuts down immediately - 🚫 No further code executes - 🚫 "finally" block is completely skipped --- 🔢 Understanding Exit Codes: - "System.exit(0)" → Normal termination ✅ - "System.exit(1)" → Abnormal termination ❌ 👉 But important point: Both will skip the "finally" block! --- ⚠️ So when does finally NOT execute? ✔️ When JVM is forcefully terminated ✔️ Using "System.exit()" ✔️ JVM crash / system failure ✔️ Infinite loop (control never reaches finally) --- 🧠 Interview Takeaway: 👉 “Finally block executes in almost all cases, except when JVM terminates abruptly like with System.exit().” --- 🔥 This is one of the most asked tricky Java interview questions! 💬 Did you know this before? #Java #JavaDeveloper #CodingInterview #Programming #TechTips #Developers #InterviewQuestions #JavaBasics

This is a fantastic point about the nuances of `finally` blocks in Java, and it's definitely a common interview gotcha! It's a great reminder that understanding edge cases is just as important as knowing the core concepts when preparing for technical roles. 👍

Like
Reply

Please check your dm

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories