share

Sunday, 8 February 2015

Finally Block In Java

Finally block always execute after try catch block.

1.
 package exception_handling;

public class FinallyBlock {
           
public static void main(String[] args) {
try {
int i=10/0;
} catch (Exception e) {
System.out.println(e);
}
finally{
System.out.println("You Are In Finally Block");
}
}
}


Output:
java.lang.ArithmeticException: / by zero
You Are In Finally Block

2.

package exception_handling;

public class FinallyBlock {
            
public static void main(String[] args) {
try {
int i=10/10;
} catch (Exception e) {
System.out.println(e);
}
finally{
System.out.println("You Are In Finally Block");
}
}
}

Output:
You Are In Finally Block

3. If You Use Return Statement in try /catch block then finally always execute  

package exception_handling;

public class FinallyReturn {
int display(){
try {
System.out.println("In display try"); 
return 2;
} catch (Exception e) {
System.out.println(e);
}finally{
System.out.println("Hi Finally Here");
}
return 1;
}
public static void main(String[] args) {
FinallyReturn finallyReturn=new FinallyReturn();
finallyReturn.display();
}
}

Output:
In display try
Hi Finally Here


4. If we use exit(0) in  try block then finally block will not execute.
package exception_handling;

public class FinallyExit {

public static void main(String[] args) {
try {
System.out.println("welcome Dear");
System.exit(0);
} catch (Exception e) {
System.out.println(e);
}finally{
System.out.println("Welcome In Finally Block");
}
}
}

Output:
welcome Dear

No comments:

Post a Comment