Does finally always execute in Java?

Ads
 

Does finally always execute in Java?

Hi,

I am learning exception handling in Java. I want to know if finally{} block is always executed or not in Java?

Does finally always execute in Java?

Thanks

View Answers

January 7, 2018 at 3:31 AM

Hi,

Yes finally{} block is always executed in Java program. It is not executed if program crashes, or System.exit(0) method is called in program.

It is also not executed if JVM crashes.

Its is also not executed if Java process is killed from OS.

Here is simple example of try catch and finally block example:

package net.roseindia;

public class FinallyBlock {
    public static void main(String args[]) {
        try {
            int a = 5 / 0;
        }

        catch (ArithmeticException e) {
            System.out.println(e);
        }

        finally {
            System.out.println("Inside finally block");
        }
    }
}

Here is output of the program:

java.lang.ArithmeticException: / by zero
Inside finally block

So, finally block is always executed in Java.

More examples:

Thanks

Ads









Related Tutorials/Questions & Answers:
Does finally always execute in Java?
Finally in java
Advertisements
difference between java5 and java6 - Java Beginners
Java2
about java1
Javah
About Java2
The finally Keyword
javaa swings - IDE Questions
Javap Tool application
finally block
try and finally block
Artifacts of javax
finally in flex
Finally() in Java
Javah -  Header File Generator
javax - JSP-Servlet
Javac -source KeyTest.java
Version of javax>javaee-api dependency
z-index always on top
Example to show Finally exception in java
Java finally
closing connections in finally block
Version of javax>javaee-endorsed-api dependency
Version of javax>javaee-web-api dependency
javac complier not found - JSP-Servlet
java.lang.NoClassDefFoundError: javax/transaction/UserTransaction????? - Struts
javax servlet error - JSP-Servlet
Write a program that replaces a, e, i, o, u in Java2
javab - Java Beginners
javas - JSP-Servlet

Ads