2

Possible Duplicate:
Why use Finally in Try … Catch

Why should we not use the catch block to clean up code?

I have not used the error-handling techniques as much, but am starting to use them for just about every program now. about time

So, while going through articles/documentations, i came across the finally block.

And as it suggests, the finally block runs irrespective of whether there is an exception or not(Of course it wont run, if there is a forced shutdown of the JVM or the PC). Also finally block is usually used for cleaning up code(resources).

So basically, if my code does not have an exception coming up, then why should i clean up the code. Shouldn't i put the cleanup code in the catch block rather than the finally block.

I tried looking for questions similar, but none asked this question it seems. So i went ahead and created a question :D

Community
  • 1
  • 1
Umang Desai
  • 428
  • 2
  • 5
  • 14
  • 1
    A classic example is file resources, that need to be closed whether you run into an exception or not. – NullUserException Oct 30 '12 at 23:29
  • 1
    @DNA That's a VB.NET question. – Robert Harvey Oct 30 '12 at 23:31
  • Or a database connection. Whether you get an exception or not, you should always free your db connection. – Jackson Oct 30 '12 at 23:31
  • 1
    Exceptions aren't the only time you will want to cleanup, either. For instance, if you are reading from an inputstream, you will want to close the stream whether an exception occurs or not, so putting it in the finally block guarantees it will be called. – rees Oct 30 '12 at 23:32
  • @Robert Harvey How embarrassing! Clearly time for me to go to bed. But looking at it again, I'm not sure it matters much in this case - the concept and reasoning is the same. – DNA Oct 30 '12 at 23:34
  • Another point - exceptions aren't the only kind of `throwable`. An `error` is a throwable as well, but it is by design a type of throwable that should not be caught. If your cleanup is in an exception catch block, then it may not execute in the case of an error. – rees Oct 30 '12 at 23:35
  • But then what if the cleanup code in interfering with my code, in which case i would want it to run only if an exception is caught. I have placed a flag which sets true if an exception occurs. Is this a bad practice? because wouldnt this be the same as setting up the cleanup code in the catch block. – Umang Desai Oct 31 '12 at 01:02

2 Answers2

7

Because the catch block is not guaranteed to execute. The finally block does have such a guarantee, unless you kick the power cord out of the wall.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • 2
    or you call `System.exit()`... or your CPU [gets hit by a cosmic ray](http://stackoverflow.com/questions/2580933/cosmic-rays-what-is-the-probability-they-will-affect-a-program)... – NullUserException Oct 30 '12 at 23:32
  • 2
    Or if Earth is destroyed by aliens. – Dmitri Oct 30 '12 at 23:34
  • But then what if the cleanup code in interfering with my code, in which case i would want it to run only if an exception is caught. I have placed a flag which sets true if an exception occurs. Is this a bad practice? because wouldnt this be the same as setting up the cleanup code in the catch block. – Umang Desai Oct 31 '12 at 01:53
  • 1
    An exception happens when the code "throws up its hands" and says "Something bad happened; I don't know what to do now, so I'm going to throw." You can decide to handle it, or rethrow, or simply allow the exception to go up the call stack and let someone else handle it. Under those conditions, you have to assume that the thing which is about to be cleaned up is in an invalid state anyway, or you can simply try something else in the `catch`. The `finally` won't execute until your code in the `catch` finishes executing, giving you time to complete your work, whatever that is. – Robert Harvey Oct 31 '12 at 02:06
1

as @RobertHarvey pointed out, the catch block is not guaranteed to execute, so the finally block is to avoid using such kind of code to make your code clearer:

    try
    {
        // do something
    }
    catch(Exception e)
    {
        // error handling
        // clean up
    }
    // clean up

so that you can make it like this:

    try
    {
        // do something        
    }
    catch(Exception e)
    {
        // error handling
    }
    finally
    {
        // clean up
    }

The finally block will help you if you wanted the first code of being executed, i.e. you wanted to clean up (closing a file for instance) either if you got an exception or not, if you just want to clean up if an error occurred you CAN clean up in the catch block.

HericDenis
  • 1,364
  • 12
  • 28