Finally block in java can be used to put CLEANUP code such as closing a file, closing connection etc. Java finally block is always executed whether exception is handled or not. Yet there are two situations where finally block won't execute.
1. When we use System.exit()
then program will automatically terminate and finally block will not get a chance to execute.
public class Test { public static void main(String args[]) { try { int i = 10/0; } catch (Exception ex) { System.out.println("Incide catch"); System.exit(1); } finally { System.out.println("Incide finally"); } } } Output : Incide catch
In above example the finally
is not getting executed due to the call of System.exit(1);
2. When there ocurs an exception in finally
block
public class Test { public static void main(String args[]) { try { int i = 10/0; } catch (Exception ex) { System.out.println("Incide catch"); } finally { int j = 10/0; System.out.println("Incide finally"); } } } Output: Incide catch Exception in thread "main" java.lang.ArithmeticException: / by zero at Test.main(Test.java:14)
Hope you have enjoyed reading When does finally block not execute in Java? Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp