FINALLY BLOCK

 
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
Finally block is used to write cleanup code such file closing,closing connection.
Finally bolck can be used with catch or alone also with try block.
 
Sequence of Finally execution

java finally keyword

Scenerion 1
When Exception Occurs

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MultipleCatch
    {
        public static void main(String[] args)
            {
                int a[] = new int[3];
                try
                    {
                        System.out.println(a[3]);
                    }
                catch (ArrayIndexOutOfBoundsException ae)
                    {
                        System.out.println("Exception happen in Exception Block :" + ae);
                    }
                finally
                    {
                        System.out.println("finally block of the code");
                    }
                System.out.println("Rest part of the programme...");
            }
    }

O/P:

java finally keyword

Scenerion 2
When Exception Does not Occurs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MultipleCatch
    {
        public static void main(String[] args)
            {
                int a[] = new int[3];
                try
                    {
                        System.out.println(a[2]);
                    }
                catch (ArrayIndexOutOfBoundsException ae)
                    {
                        System.out.println("Exception happen in Exception Block :" + ae);
                    }
                finally
                    {
                        System.out.println("finally block of the code");
                    }
                System.out.println("Rest part of the programme...");
            }
    }

O/P:

java finally keyword

When finally block will be not executed?
If the JVM exits while the try or catch code is being executed, then the finally block may not execute.
If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
 
What is the benefit of the finally block?
Since finally block runs either exception handled or not,this block is very usefull for writing cleanup code.