Advertisement
//Java - Finally Block
class A
{
public static void main(String... ar)
{
try
{
A ob = new A ();
}
catch(Exception e)
{
System.out.println( "Exception caught"+e);
}
finally
{
System.out.println("A finally block is executed irrespective of an exception is thrown or not");
}
}
}
A finally block is executed irrespective of an exception is thrown or not
//Java - Finally Block
class A
{
public static void main(String... ar)
{
try
{
Integer i = new Integer("One");
}
catch(Exception e)
{
System.out.println("Exception caught - "+e);
}
finally
{
System.out.println("A finally block is executed even after an exception is caught in the catch-block");
}
}
}
Exception caught - java.lang.NumberFormatException: For input string: "One"
A finally block is executed even after an exception is caught in the catch-block
Advertisement
//Java - Finally Block
class A
{
public static void main(String... ar)
{
try
{
A ob = null;
System.out.println(ob.toString()); //calling toString() on null reference throws NullPointerException
}
catch(ArithmeticException e)
{
System.out.println("Exception caught - "+e);
}
finally
{
System.out.println("A finally block is executed even after an exception is not caught in the catch-block");
}
}
}
A finally block is executed even after an exception is not caught in the catch-block
Exception in thread "main" java.lang.NullPointerException
at A.main(Ex13.java:8)
//Java - Finally Block
class A
{
public static void main(String... ar)
{
try
{
A ob = null;
System.out.println(ob.toString());
}
finally
{
System.out.println("A finally block is executed in the absence of catch-block, when exception is thrown.");
}
}
}
A finally block is executed in the absence of catch-block, when exception is thrown.
Exception in thread "main" java.lang.NullPointerException
at A.main(Ex13.java:8)
//Java - Finally Block
class A
{
public static void main(String... ar)
{
try
{
A ob = new A();
}
finally
{
System.out.println("A finally block is executed in the absence of catch-block, when exception is not thrown.");
}
}
}
Output-
A finally block is executed in the absence of catch-block, when exception is not thrown.
//Java - Finally Block
import java.io.*;
public class Finally
{
public static void main(String... ar)
{
FileWriter fileWriter = null;
try
{
File file = new File("D:\\File.txt");
fileWriter = new FileWriter(file); //creating a file
fileWriter.write("Hello Java"); //writing data to a file
fileWriter.flush(); //flushes the data to a file
} //try block ends
catch(IOException e)
{
e.printStackTrace();
} //catch block ends
finally
{
try
{
fileWriter.close(); //cleaning up the resources i.e. closing an opened file.
}
catch(IOException e)
{
System.out.println(e);
}
} //finally block ends
}
}
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement