Friday, December 12, 2008

Simple Java Program to understand finally Block

/*------------------------------------------------------------------------
Simple Java Program to understand finally Block
------------------------------------------------------------------------*/
class finallyexample{
public static void main(String args[]){
int i,total=0;
try{
for(i=0;i<3;i++){
System.out.println(args[i]);
total+=Integer.parseInt(args[i]);//converting string to integer
}
System.out.println(" The total is " + total);
//this block is executed only when number of arguments is 3 or more }
catch (ArrayIndexOutOfBoundsException a){
//this block is executed only when number of arguments is less than 3
System.out.println("A minimum of 3 arguments are required");
} finally{
//this block is executed irrespective of the number of arguments passed to the program
System.out.println(" The total is " + total); } }}
/*------------------------------------------------------------------------
Output with the "finally" block
------------------------------------------------------------------------
C:\j2sdk1.4.2_04\bin>javac finallyexample.java
C:\j2sdk1.4.2_04\bin>java finallyexample 1 2 3
1
2
3
The total is 6
The total is 6
C:\j2sdk1.4.2_04\bin>java finallyexample 1 2
1
2
A minimum of 3 arguments are required
The total is 3
------------------------------------------------------------------------*/

No comments: