CodingBison

All the statements inside the finally block will be executed at the end of a try/catch block. Also, the statements inside finally block will be always executed (either way exception is hit or not). In the below example, even if the result is less than 200 and no exception has been hit at the run time, the statements inside finally block will still be executed. The "finally" code is used when an application want to close some sockets, file descriptor(fd), free some memory etc. A "finally" is optional, a catch block could be replaced by a finally block; try/finally or try/catch or try/catch/finally.

 // Notice the addition of finally block at the end of try/catch blocks.
 public class exceptionHandlingExample {
     public static void main(String[] args) {
         int result = 0;
         int var1= 200;

         try { // Try Block -1
             System.out.println(" Try Block-1: This statement is executed");
             result =  var1+10;
             if (result > 200) {
                 throw new ArithmeticException(" Result above 200");
             }
             // Any thing below this will not be executed.
             System.out.println(" This statement is not executed");
         } catch(ArithmeticException e1)  {
             System.out.println(" Try Block-1:Catch Block, Arithmetic Exception " + e1);
             result = 199; // Self correction, we may want to set result to 1.
         } catch (Exception e2) {
             System.out.println(" Try Block-1:Catch Block, Generic Exception");
         } finally {
             System.out.println (" This is the finally statement");
         }

         result = result + 1;
         System.out.println(" This is executed, Result: " + result);
     }
 }

Compile/Run this program and here is the output:

  Try Block-1: This statement is executed
  Try Block-1:Catch Block, Arithmetic Exception java.lang.ArithmeticException:  Result above 200
  This is the finally statement
  This is executed, Result: 200




comments powered by Disqus