Does finally always execute in Java?

 
 

Share on Google+Share on Google+

Java Coder
Does finally always execute in Java?
1 Answer(s)      15 days ago
Posted in : Java Beginners
Ads

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

Ads
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









Ads

 
Advertisement null

Ads