freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Finally block:-

1) finally is a block it is always executed irrespective of try and catch.
2) Finally contains clean-up code.
3) It is not possible to write finally alone . we must take try-catch-finally otherwise take the try-finally these two are the possibilities. If we are taking any other we are getting compilation error saying finally without try block .

Java Images

Syntax:-
try
{
risky code;
}
catch (Exception obj)
{
handling code;
}
finally
{
free code;
}

Exception raised in try block and corresponding catch block is matched then rest of the code is executed normally.

class Test
{
public static void main(String[] args)
{
try
{
System.out.println(10/0);
}
catch (ArithmeticException ae)
{
System.out.println("u r getting ae:"+ae);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code");
}
}

intput and output

output:U r getting ae:ArithmeticException : /by zero Finally block is always executed

with out Exception finally block is executed

class Test
  {
public static void main(String[] args)
  {
try
  {
System.out.println("freetimestudy");
  }
finally
{
System.out.println("finally block");
 }
  }
 };

intput and output

output:freetimestudy finally block