Finally is the block of code that executes always. The code in finally
block will execute even if an exception is occurred. Finally block is
NOT called in following conditions
1.public class TryCatchFinally {
public static void main(String ar[]){
try{
System.out.println("try block");
}
catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
int x=0;
if(x>1){
System.out.println("finally block");
}
}
}
}
output:
try block
2. public class TryCatchFinally {
public static void main(String ar[]){
try{
System.out.println("try block");
System.exit(0);
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
System.out.println("finally block");
}
}
}
output:
try block
3. public class TryCatchFinally {
public static void main(String ar[]){
try{
int x=0;
if(x<1){
throw new Exception();
}
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
int x=0;
if(x>1){
System.out.println("finally block");
}
}
}
}
output:
catch block
4. public class TryCatchFinally {
public static void main(String ar[]){
try{
int x=0;
if(x<1){
throw new Exception();
}
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
System.out.println("finally block");
}
}
}
output:
catch block
1.public class TryCatchFinally {
public static void main(String ar[]){
try{
System.out.println("try block");
}
catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
int x=0;
if(x>1){
System.out.println("finally block");
}
}
}
}
output:
try block
2. public class TryCatchFinally {
public static void main(String ar[]){
try{
System.out.println("try block");
System.exit(0);
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
System.out.println("finally block");
}
}
}
output:
try block
3. public class TryCatchFinally {
public static void main(String ar[]){
try{
int x=0;
if(x<1){
throw new Exception();
}
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
int x=0;
if(x>1){
System.out.println("finally block");
}
}
}
}
output:
catch block
4. public class TryCatchFinally {
public static void main(String ar[]){
try{
int x=0;
if(x<1){
throw new Exception();
}
}catch(Exception e){
System.out.println("catch block");
System.exit(0);
}finally{
System.out.println("finally block");
}
}
}
output:
catch block