The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection. Before terminating the program, JVM executes finally block.
Example:
class Simple{
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…”);
}
}
Output:
Output:5
finally block is always executed
rest of the code…
For finally block. finally block is executed even if Exception occurs or not.
Import java.io.*;
class ex1 {
public static void main(String args[]) throws IOException
{
int a,b;
DataInputStream br=new DataInputStream(System.in); a=Integer.parseInt(br.readLine()); b=Integer.parseInt(br.readLine());
try
{
System.out.println(a/b);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
System.out.println(“Work necessary”);
}
}
}