Java

Java – Finally Block – Exception Handling

I discussed try-catch blocks and nested try blocks in earlier courses. This article will show how finally blocks, which are used with try-catch, are utilized.
All the essential sentences that must be carried out whether an exception occurs or not are included in a finally block. No matter whether an exception happens in the try block or not, the statements provided in this block, such as shutting a connection or stream, will always be carried out.

Syntax of Finally block

try {
    //Statements that may cause an exception
}
catch {
   //Handling exception
}
finally {
   //Statements to be executed
}

A Simple Example of finally block

Here, you can see that the try block handled the exception, which was then followed by the execution of the end block.

class Example
{
   public static void main(String args[]) {
      try{  
	 int num=121/0;  
	 System.out.println(num);  
      }  
      catch(ArithmeticException e){
         System.out.println("Number should not be divided by zero");
      }  
      /* Finally block will always execute
       * even if there is no exception in try block
       */
      finally{
	 System.out.println("This is finally block");
      }  
      System.out.println("Out of try-catch-finally");  
   }   
}

Output:

Number should not be divided by zero
This is finally block
Out of try-catch-finally

Few Important points regarding finally block

1. You cannot use finally without a try block; instead, a finally block requires a try block. Put any statements in this block that need to run continuously.

2. The try-catch block is adequate for managing exceptions, as we’ve seen in earlier lessons. However, if you include a finally block, it will always execute after the try block has finished running.

3. The finally block is run after the try block in the regular scenario when there is no exception in the try block. However, the catch block is run before the finally block if an exception occurs.

4. A finally block exception functions precisely like any other exception.

5. The finally block’s assertions are carried out even when the try block includes control-transfer clauses like return, break, or continue.
Let’s look at an example to show how finally works when the try block contains a return statement:

Another example of finally block and return statement

You can see that the finally block continues to function even when the procedure contains a return statement.

class JavaFinally
{
   public static void main(String args[])
   {
      System.out.println(JavaFinally.myMethod());  
   }
   public static int myMethod()
   {
      try {
        return 112;
      }
      finally {
        System.out.println("This is Finally block");
        System.out.println("Finally block ran even after return statement");
      }
   }
}

Output of above program:

This is Finally block
Finally block ran even after return

Cases when the finally block doesn’t execute

The following events prohibit the code in a finally block from running:

  • The death of a thread
  • The use of the System. exit() function.
  • As a result of a finally block exception.

Finally and Close()

All open streams in a program are closed using the close() command. Use of close() within a finally block is recommended. You can be confident that all input and output streams are correctly closed whether or not an exception happens since the finally block runs even if one occurs.

For instance:

....
try{ 
    OutputStream osf = new FileOutputStream( "filename" );
    OutputStream osb = new BufferedOutputStream(opf);
    ObjectOutput op = new ObjectOutputStream(osb);
    try{
       output.writeObject(writableObject);
    }
    finally{
       op.close();
    }
}
catch(IOException e1){
     System.out.println(e1);
}
...

Finally block without catch

It is possible to use a try-finally block without a catch block. This implies that finally may be used with a try block without a catch block.

...
InputStream input = null;
try {
    input = new FileInputStream("inputfile.txt");
} 
finally {
    if (input != null) {
       try {
         in.close();
       }catch (IOException exp) {
           System.out.println(exp);
        }
    }
}
...

Finally block and System.exit()

Those using System.exit() operate differently than statements using Return. In contrast to return statements, finally block does not run whenever System.exit() is used in a try block. Here is a sample code to illustrate the same:

....
try {
   //try block
   System.out.println("Inside try block");
   System.exit(0)
}
catch (Exception exp) {
   System.out.println(exp);
}
finally {
   System.out.println("Java finally block");
}
....

If System.exit(0) is invoked in the aforementioned example without any exceptions, the program won’t ultimately run. However, the finally block will be performed if any exception happens when invoking System.exit(0).

try-catch-finally block

  • Either a catch block or finally should be connected to a try statement.
  • The ideal strategy is to utilize both catch and cleanup since catch handles exceptions and cleanup is what it does at the end.

Syntax:

try {
     //statements that may cause an exception
}
catch (…)‏ {
     //error handling code
}
finally {
    //statements to be executed
}

Examples of Try catch finally blocks

Example 1: The following illustration shows how the finally block functions when the try block throws no exceptions.

class Example1{
  public static void main(String args[]){
    try{
       System.out.println("First statement of try block");
       int num=45/3;
       System.out.println(num);
    }
    catch(ArrayIndexOutOfBoundsException e){
       System.out.println("ArrayIndexOutOfBoundsException");
    }
    finally{
       System.out.println("finally block");
    }
    System.out.println("Out of try-catch-finally block");
  }
}

Output:

First statement of try block
15
finally block
Out of try-catch-finally block

Example 2: The following example demonstrates how the finally block functions when a try block exception occurs but is not handled by a catch block:

class Example2{
   public static void main(String args[]){
     try{
        System.out.println("First statement of try block");
        int num=45/0;
        System.out.println(num);
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("ArrayIndexOutOfBoundsException");
     }
     finally{
        System.out.println("finally block");
     }
     System.out.println("Out of try-catch-finally block");
   }
}

Output:

First statement of try block
finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at beginnersbook.com.Example2.main(Details.java:6)

As you can see, the finally block was successfully performed before the system-generated error message was shown.

Example 3: when an exception is caught in a catch block after occurring in a try block

class Example3{
   public static void main(String args[]){
      try{
         System.out.println("First statement of try block");
         int num=45/0;
         System.out.println(num);
      }
      catch(ArithmeticException e){
         System.out.println("ArithmeticException");
      }
      finally{
         System.out.println("finally block");
      }
      System.out.println("Out of try-catch-finally block");
   }
}

Output:

First statement of try block
ArithmeticException
finally block
Out of try-catch-finally block

 

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button