Tuesday, January 25, 2011

Finally execute the code… no matter what happens…

Here we use try finally to execute essential code, even if any severe error happens.

But when you try to kill the program the finally code will not be executed.


class TryFinallyTest{

public static void main(String[] args){

try{

double value = Double.parseDouble(args[0]);

double result = Math.sqrt(value);

System.out.printf("Square-root of %f is %f%n",

value, result);

}finally{

System.out.println("Goodbye!");

}

System.out.println("Done!");

}

}


To compile:

javac TryFinallyTest.java

To run:

java TryFinallyTest

No comments: