How finally used under Exception Handling?

0 votes
asked Jun 29, 2016 in Java by Nani
, , 95 views Last updated : Dec 13, 2017

3 Answers

0 votes
The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred.
answered Jun 29, 2016 by Naveen
0 votes

In 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 is handled or not. By the following examples u can observe exception handling

----In this case exception occurs and not handled.

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...");
  }
}

-------In this case 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...");
  }
}

answered Feb 9 by ajaykumar
0 votes

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 is handled or not.

Java finally block follows try or catch block.

  • Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
answered Feb 9 by muneshs16

Related questions

Why Vector class is used?

Vector implements a dynamic array. It is similar to ArrayList, but with two differences − Vector is synchronized. Vector contains many legacy methods that are not part of the collections...

solved
java, jdbc, servlet 2 Answer 81 views asked Jul 28, 2016 in Java by Satish