Java Finally block is a block that is used to execute important code such as closing connection, stream etc.
Java Finally block is always executed whether exception handles or not.
Finally, block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
For each try block, there can be zero or more catch blocks, but only one finally block
The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). Ref - https://teck4world.blogspot.com/2018/05/systemexitint-x.html
- class TestFinallyBlock{
- public static void main(String args[]){
- try{
- int data=25/5;
- System.out.println(data);
- }
- catch(NullPointerException e){System.out.println(e);}
- finally{System.out.println("finally block is always executed");}
- System.out.println("rest of the code...");
- }
- }
- class TestFinallyBlock1{
- public static void main(String args[]){
- try{
- int data=25/0;
- System.out.println(data);
- }
- catch(NullPointerException e){System.out.println(e);}
- finally{System.out.println("finally block is always executed");}
- System.out.println("rest of the code...");
- }
- }
Case 03 - The exception occurs and handled.
- public class TestFinallyBlock2{
- public static void main(String args[]){
- try{
- int data=25/0;
- System.out.println(data);
- }
- catch(ArithmeticException e){System.out.println(e);}
- finally{System.out.println("finally block is always executed");}
- System.out.println("rest of the code...");
- }
- }
No comments:
Post a Comment