Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top