Welcome to Srini's blog

Monday, April 19, 2010

Is it possible to prevent "finally" block execution ?? -- Java

finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch
statement matches the exception. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns.

Now I will tell you an interesting thing about finally. Consider the case. I have a try, catch, finally blocks in my code and I have a requirement like finally block should be executes only if any exception raised otherwise it should not be executed. From the above if there is finally block in your code then it must be executed. How can i solve this ?
Ans : we can able to prevent the finally block execeution by using System.exit(0). see the example below.

try {
String s1 = "abc";
String s2 = "abc";
if(s1.equals(s2)) {
System.exit(0);
} else {
throw New Exception("Both Strings are equal);
}
} catch(Exception e) {
System.out.println(e.getMessage());
} finally {
System.out.println("Finally block executed");
}

Try this example with different strings you may get some idea.

2 comments:

  1. No dude .. its worked for me. may be some syntax errors in my code, correct it and try. Dont try like just copy the code and run, understand the usage of "System.exit()" ...

    ReplyDelete