Quantcast
Channel: Learn Java Programming
Viewing all articles
Browse latest Browse all 39

Finally block : Exception Handling in Java Programming

$
0
0

In the previous chapter we have studied the nested try and catch blocks in this chapter we will be learning the finally block.

Finally block : Exception Handling in Java

  1. Finally Block in always executed irrespective of exception is handled or not
  2. Finally is not a function, It is keyword in java
  3. Finally performs the functions such as closing the stream or file and closing connections.
  4. Finally block always gets executed before terminating the program by JVM.
  5. Finally block should be after try and catch and is optional
  6. Each try block has minimum 0 and maximum 1 finally block.

Flowchart for finally block -

Finally Block in Java Programming

Finally block : Syntax

try {
-------
-------
} catch(Exception e) {
-------
-------
}
finally {

}

Tip 1 : Finally block is optional

In the program we can have minimum zero and maximum one finally block.

public class MyExceptionExample {
    public static void main(String[] a){
        
        try{
            int i = 10/0;
        } catch(Exception ex){
            System.out.println("Inside 1st catch Block");
        }
        

        try{
            int i = 10/10;
        } catch(Exception ex){
            System.out.println("Inside 2nd catch Block");
        } finally {
            System.out.println("Inside 2nd finally block");
        }
    }
}

In the 1st try block we can see that we don’t have finally block but in the 2nd try block we have finally block. So finally block is always optional.

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

2nd try block does not throw any exception but still after the execution of try block code executes finally block

Output :

Inside 1st catch Block
Inside 2nd finally block

Tip 2 : Finally block is not executed in below two cases

  1. If following statement is included in the try block (Terminating code using system exit)
  2. System.exit(0);
    
  3. If the thread executing the try or catch code is interrupted or killed, the finally block may not execute [For more info]

The post Finally block : Exception Handling in Java Programming appeared first on Learn Java Programming.


Viewing all articles
Browse latest Browse all 39

Trending Articles