
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Is finally block always get executed in Java?
Yes, the finally block is always get executed unless there is an abnormal program termination either resulting from a JVM crash or from a call to System.exit().
- A finally block is always get executed whether the exception has occurred or not.
- If an exception occurs like closing a file or DB connection, then the finally block is used to clean up the code.
- We cannot say the finally block is always executes because sometimes if any statement like System.exit() or some similar code is written into try block then program will automatically terminate and the finally block will not be executed in this case.
- A finally block will not execute due to other conditions like when JVM runs out of memory when our java process is killed forcefully from task manager or console when our machine shuts down due to power failure and deadlock condition in our try block.
Example 1
public class FinallyBlock { public static void main(String args[]){ try { int a=10,b=30; int c = b/a; System.out.println(c); } catch(ArithmeticException ae){ System.out.println(ae); } finally { System.out.println("finally block is always executed"); } } }
In the above example, the finally block always get executed if the exception has occurred or not.
Output
3 finally block is always executed
Example 2
public class FinallyBlock { public static void main(String args[]) { try { System.out.println("I am in try block"); System.exit(1); } catch(Exception ex){ ex.printStackTrace(); } finally { System.out.println("I am in finally block"); } } }
In the above example, the finally block will not execute due to the System.exit(1) condition in the try block.
Output
I am in try block
- Related Questions & Answers
- Does finally always execute in Java?
- What is the finally block in Java?
- Does code form Java finally block
- Can finally block be used without catch in Java?
- Is there a case when finally block does not execute in Java?
- Explain Try/Catch/Finally block in PowerShell
- Is there any way to skip finally block even if some exception occurs in exception block using java?
- Will a finally block execute after a return statement in a method in Java?
- Why the main () method in Java is always static?
- What is the try block in Java?
- What is the catch block in Java?
- final, finally and finalize in Java
- What is finally statement in C#?
- Java static block
- What is the difference between final, finally and finalize() in Java?
Advertisements