Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
4.60/5 (3 votes)
See more:
yesterday attended an interview and was puzzled when the interviewer asked whats the advantage of using finally block as the code below the finally will also execute.

like
try
     {
         File.OpenRead(@"c:\notihng.txt");
     }
     catch (Exception)
     {
         //gets in here when file is not found.
         // swallow exception.. yummy..:)
     }
     finally
     {
         //gets in here every time..
         //[my code]
     }
     int x2 = 123; //still executes so whats
     // the use of using finally when [my code] can be written here
     // instead of finally.
 }

then whats the use of writing the code in finally block...!
but any ways got the job..:) but wanted the answer, thought of asking the interviewer but thought this would be a nice place.
Posted
Updated 8-May-11 21:36pm
v4

Hi there,

I think everyone who posted before me has mentioned everything that you want to know :)

Just adding to that, think of finally block as something you want to do regardless what happens inside a try block (E.g.: Exception thrown, Return statement found, everything went smoothly, etc.)

The easiest is to explain it with some code.
C#
SqlConnection connection = null;
try {

    var connectionStringName = connectionComboBox.Text.Trim();
    if (connectionStringName.Length == 0) {
        MessageBox.Show("Please, select a connection");
        return;
    } else {
        connection = new SqlConnection();
        connection.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ToString();
        connection.Open();
    }

    // More code
}
catch {
    // Handle your exceptions here
    // You can even have multiple catch blocks to take care of different types of exception
    // Or if you handling exceptions at a higher level, just remove the catch block
}
finally {
    if ((connection != null) && (connection.State == ConnectionState.Open)
        try {
            connection.Close();
        }
        catch {
            // Normally, you do not want to log errors like these, so you just suppress them with an empty block
            // But if you want to handle them, you can always go ahead or just remove the catch block to handle it in a higher level
        }
}

In the above example, there are multiple instances where exceptions might be thrown, even while opening a connection. Regardless of that, you want to close the connection to the database, IF there is a connection open after the code block executes. The finally block will execute, even if the return statement is executed.

One important thing to remember is, a finally block MUST NOT throw an exception unless the system design explicitly wants you to do so, which is considered bad practice in general.

Hope this helps :) Regards
 
Share this answer
 
v3
Comments
Olivier Levrey 9-May-11 4:05am    
An example is always welcome. Have a 5.
CodeHawkz 9-May-11 4:15am    
Thank you :)
[no name] 3-Aug-14 10:59am    
+5
Code written in a finally block will execute regardless of what else happens in the try-catch.

So if you open a SqlConnection say, then in your try block you encounter a major problem and throw an exception, the code in the finally block will be executed before the throw is actioned - allowing you to close the scarce resource tidily.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 9-May-11 2:45am    
My 5, but there is OP's misconception.

I'm trying to help; please see my answer.
--SA
Olivier Levrey 9-May-11 3:57am    
I agree. 5.
Finally block always executes (in case of exception or no exception)

One use of this is to release costly resouces, which may be left unused in case of exception occurs before releasing it.

we need it to perform actions which needs to be done irrespective of any unexpected exception comes in flow.
 
Share this answer
 
Comments
Olivier Levrey 9-May-11 4:04am    
I Agree. 5.
This is the block which is always executed, even if exception was thrown, no matter of what type (one of handled types, derived from one of handled types or something else).

[EDIT]
Here is the code sample close to the one of original question.

C#
try
{
    //point 1: exception thrown or not
}
catch(ex1)
//...
catch(ex2)
//...
finally()
{
    //point 2, always executed
}
   //point 3: can be executed or not



In this sample, point 1: code may finish or throw exception. Point 2: always execute; Point 3: if exception is not thrown, will execute; it exception of the type ex1 (or derived type) is thrown, it execute if the handler of this exception does not re-throw. Same thing about ex2. When any other exception is thrown, point 3 never execute.

[END EDIT]

Note: you should not block exceptions from propagation. In most cases, you need to re-throw them. Don't handle exceptions you have no specific way of handling. Only on the top of the stack of each thread should you block exception (to avoid termination). [EDIT] In the case catch Exception all exceptions will be caught, because they all are derived from System.Exception. It makes "finally" totally redundant. The cases when you catch all exceptions should be rare; usually used for over-work of some third-party code you cannot patch.

For more directions, see:
How do i make a loop that will stop when a scrollbar reaches the bottom[^],
When i run an application an exception is caught how to handle this?[^],
throw . .then ... rethrowing[^].

—SA
 
Share this answer
 
v3
Comments
Olivier Levrey 9-May-11 4:03am    
My 5. I needed to see the previous versions of the question to see your comments about ex1, ex2, ...
It may be better to write those examples in your answer ;)
Sergey Alexandrovich Kryukov 9-May-11 9:52am    
Thank you, Olivier.
Thanks for the notes on last-version code samples; it needs some change in the answer.
--SA
yesotaso 9-May-11 7:50am    
Propagation is the key of course. If there is an exception in the try block but catch block does not cover will the code not in "finally block" work. In OP's case it doesnt matter he'd catch base exception and show MessageBox etc and move on...
Side Note: I am not very fond of rethrowing if possible let exception pass your try block. Disposing older exception and trhowing new ones clouds the objective "stack trace"
Sergey Alexandrovich Kryukov 9-May-11 10:00am    
Thank you for the note. "In OP's case it doesn't matter" rather the sign of OP's abuse of the technique. In the present version of the sample, "finally" does not matter because of "catch-all" form of exception which is really bad in most cases. Main practical rule is not about processing exception but about not catching it. Over-catching is the biggest mistake. As to re-throw -- this is not the most typical case, but sometimes it is absolutely needed. Most useful is usually not "throw", but throw with the parameter of the more semantic exception. For example "Invalid numeric format" caught, "validation exception" thrown. Even this is the relatively rare case. Most typical should be catching all at once at the top of each stack or in the UI event cycle. It depends though.
--SA
Block of statements to be executed regardless of whether or not an exception is thrown. Associated with either a try or a try-catch block. Used to guarantee an operation will be performed despite any exceptions thrown, e.g., releasing a database connection.
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 9-May-11 2:46am    
Correct answer and example, my 5, but OP has misconception on usage as well.
Please see my answer.
--SA
Olivier Levrey 9-May-11 3:53am    
I agree. 5.
Block of statements to be executed regardless of whether or not an exception is thrown. Associated with either a try or a try-catch block,finally block is executed everytime,even if there is a error or not.Basically its used to free memories,event handlers read write locks at the end of the code.
 
Share this answer
 
v4
Comments
Olivier Levrey 9-May-11 4:12am    
I don't understand who down-voted this. This answer is correct. Have a 5.
There cab be return statements either in the Try or the Catch, or
both. In this case code in the finally guarantees that it will be executed
in any case. Where as otherwise, the code below finally will not be executed.
 
Share this answer
 
Comments
Mubeen.asim 9-May-11 2:40am    
do you mean to say that if there is a return statement in a try or catch, instead of returning to the caller, the finally gets executed and then it returns..? will have to try one program on it then.
Sergey Alexandrovich Kryukov 9-May-11 2:44am    
No! Return can be there but this is a return of calling method.
Please see my answer.
--SA
Mubeen.asim 9-May-11 2:48am    
ok i guess i got it right now reading all the answers, you use a exceptional resource..! and then it causes an exception leaving the resource unusable or in a locked state. so some one has to free the resource and move on.
where as if am writing the resource freeing code below the finally block, it will not execute as the ..NO.. still confused.. it still gets executed as the catch swallows the exception.. some one give me few quick lines of code so that i could understand it better than English..:(
Olivier Levrey 9-May-11 4:11am    
Correct. 5.
when you write
MIDL
finally()
{
// the code here will also execute
}

the code under finally block will always be executed 


try this link also--

Try Catch[^]
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 9-May-11 2:47am    
Correct answer, my 5, but OP has misconception on usage as well.
Please see my answer.
--SA
Olivier Levrey 9-May-11 3:56am    
I voted 4 because this is not completely correct. The code under the finally block will execute only if there is a catch block.
Nitin S 9-May-11 6:23am    
In C# we can use try finally without catch clause @Olivier
Olivier Levrey 9-May-11 6:30am    
I know. This is why I said the above example is not correct. I didn't say the above code will not compile without catch, I said it will not execute the last part without a catch block.
Sergey Alexandrovich Kryukov 9-May-11 10:12am    
Without catch -- of course, but not without try.
--SA
ok got the thinks working now..
 public string nothing()
        {

            try
            {
                File.OpenRead(@"c:\notihng.txt");
            }
            catch (Exception)
            {
                //gets in here when file is not found.
                // swallow exception.. yummy..:)
                return "will this return..?";// will be returned
            }
            finally
            {
            }
            int x2 = 123; //still executes so whats
            // the use of using finally when [my code] can be written here
            // instead of finally.
            return "or this..?"; //will not be returned
        
}


So when ever you have a return statement or when you need to return some thing in case of exceptions then i guess we have to use the finally or it does not make any sense in writing a finally block which is optional
 
Share this answer
 
Comments
Olivier Levrey 9-May-11 4:09am    
Don't post a question as an answer. Please update your question or post a comment under a specific answer to gove feedback to the poster.

To answer your question here: since you have a return statement in the catch block, if an exception is raised, all code after the finally block will be skipped. If you want int x2 = 123; to be executed in any case (exception or not), then you need to put it inside the finally block.
In this example, the code will be executed only if no exception is raised.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900