Friday, March 25, 2016

Use finally Block carefully

One should be careful on using finally block.
Finally block should be used only to close any resource, or avoid using it if resource implements AutoClosable interface.
Few bad usage of finally :

Bad Usage 1:  do not return a value from finally. It will override the value returned from try block.
 
   public int getValue(){
try{
return 10;
}finally{
return 20;
}
}

getValue() will return 20;

Bad Usage 2: Do not eat an exception thrown in try with some unrelavent exception/or a return value in finally .

     public int getValue(){
try{
throw new Exception("a exception");
}finally{
return 20;
}
}

We will have no idea about an exception that has occurred in getValue(). 
   

No comments:

Post a Comment