Finally Block. Use But Carefully






Finally clause is a block that guarantees that this block will be executed whether there is exception occurred in try-catch block on not. If we call system.exit(0) then finally block will not be executed.  
You can use the finally clause without a catch clause. For example, consider the following
try statement:

Graphics g = image.getGraphics();
try{code that mightthrow exceptions}finally{g.dispose();}


The g.dispose() command in the finally clause is executed whether or not an exception is
encountered in the try block.


Point to remember using finally block:

The finally clause leads to unexpected control flow when you exit the middle of a try block with a return statement. Before the method returns, the contents of the finally block is executed. If it also contains a return statement, then it masks the original return value. 

Consider this  example:

public static int f(int n)
{
try
{
int r = n * n;
return r;
}
finally
{
if (n == 2) return 0;
}

}



If you call f(2), then the try block computes r = 4 and executes the return statement. However, the finally clause is executed before the method actually returns. The finally clause causes the method to return 0, ignoring the original return value of 4.


Sometimes the finally clause gives you grief, namely if the cleanup method can also throw an exception. A typical case is closing a stream.Suppose you want to make sure that you close a stream when an exception hits in the stream processing code.


InputStream in;


try
{
code that might
throw exceptions
}
catch (IOException e)
{
show error dialog
}
finally
{
in.close();
}


Now suppose that the code in the try block throws some exception other than an IOException that is of interest to the caller of the code. The finally block executes, and the close method is called. That method can itself throw an IOException! When it does, then the original exception is lost and the IOException is thrown instead. That is very much against the spirit of exception handling.





0 comments:

Post a Comment

 
Copyright (c) 2013 Java Discovery.