"FINALLY" BLOCKS

CONTENTS

1. Introduction
2. Example


1. INTRODUCTION

Java allows a programmer to define a block of code that is guaranteed to be executed what ever happens. Such a block is known as a finally block and has the form:

 
finally {
   ....
   }

and must follow a try block.



2. EXAMPLE

Consider the method presented in Table 1. If the second argument is 0 the method will returnm without doing the division and without outputing string END. In Table 2 we have included a finally block coupled with a try block. In this case the statements within the finally block will always be executed reqardless of the return statement invoked when the seconf argument is equivalent to 0, i.e. the END string will always be output.

public static void division(int num1, int num2) {

    if (num2 == 0) return;
    
    System.out.println("Division   = " + num1/num2);
    System.out.println("END");
    }

Table 1:Example method

public static void division(int num1, int num2) {

    try {
	if (num2 == 0) return;
	System.out.println("Division   = " + num1/num2);
	}
    finally {
	System.out.println("END");
	}	    
    }

Table 2:Finally block example




Created and maintained by Frans Coenen. Last updated 29 March 2000