Finally
There will be some situations where we have to perform some action while bypassing from try catch throw clauses.
Ex: To close a file which is used in before.
// Demonstrate finally.
public class FinallyDemo
{
// Throw an exception out of the method.
static void procA()
{
try
{
System.out.println("inside procA");
throw new RuntimeException("demo"); //even throw an exception it will throw after executing finally block.
}
finally
{
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB()
{
try
{
System.out.println("inside procB");
return; //return within a try block but it will execute finally block
}
finally
{
System.out.println("procB's finally");
}
}
// Execute a try block normally.
static void procC()
{
try
{
System.out.println("inside procC");
}
finally
{
System.out.println("procC's finally");
}
}
public static void main(String args[])
{
try
{
procA();
}
catch (Exception e)
{
System.out.println("Exception caught"); //will catch the Run-time Exception in procA();
}
procB(); //call to procB()
procC();
}
}
Output:
inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally