You are here: Home / Topics / Finally block example in Java

Finally block example in Java

Filed under: Java on 2023-09-19 06:49:11

// Program to use finally Block with exception handling.

class  finallyBlockWithException
{
// Through an exception out of the method.
static void procA() 
{
 try 
 {
  System.out.println("inside procA");
  throw new RuntimeException("demo");
 } 
 finally 
 {
  System.out.println("procA's finally");
 }
}

// Return from within a try block.
static void procB() 
{
 try 
 {
  System.out.println("inside procB");
  return;
 } 
 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");
 }
 procB();
 procC();
}
}


Output:

inside procA
procA's finally
Exception caught
inside procB
procB's finally
inside procC
procC's finally


About Author:
M
Mr. Dubey     View Profile
Founder of MCQ Buddy. I just like to help others. This portal helps students in getting study material free. Share your stuff here so that others can get benefitted.