[.net] finally clause of C-sharp

Started by
4 comments, last by markr 19 years, 8 months ago
i have got this lil confusion on the "finally" clause of C-sharp unfortunately i dont have the c-sharp compiler with me right now :S consider the following example

try{
...
...
}
catch(Exception e)
{
...
...
}
finally{
    Console.WriteLine( " i am inside the finally" );
}

Console.WriteLine( " i am outside the try block" );

If, there were no exception in the try block then shouldn't be the output like i am inside the finally i am ouside the try block The confusion is.. the book i am reading says the , "if there is no exception in the try block then the finally block will be executed right before the function goes out of scope" which my gut feelings says "NO".
Z
Advertisement
The code in finally will always execute. Exception throwed or not.

EDIT: The code in finally will always execute, and it will execute before any code below the finally block executes.
Arguing on the internet is like running in the Special Olympics: Even if you win, you're still retarded.[How To Ask Questions|STL Programmer's Guide|Bjarne FAQ|C++ FAQ Lite|C++ Reference|MSDN]
well I know that finally will be always executed...but i want to know WHEN ? , i mean the order of execution is what i want to know... will it be executed before the function goes out ot scope or will it be executed right atfter the completion of the try block
Z
You're correct, the book is wrong (or maybe just improperly worded)

The finally clause will get executed when control flow leaves the try / catch block, regardless of whether there was an exception or not. So your output is correct.

What book is it that you're reading? We should submit an entry for its errata.



-Alias
Quote:Original post by browny
The confusion is.. the book i am reading says the , "if there is no exception in the try block then the finally block will be executed right before the function goes out of scope" which my gut feelings says "NO".


Your book is assuming that you would surround the entire function with the try-catch-finally block. The finally block will execute at the end of teh try or the end of the catch block. Any code after the finally block will be executed in sequential order...

In other words, the book is wrong.

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

The "finally" block will be executed EVEN if there is an exception in the catch() block.

The whole point of "finally" is it always gets executed. Even if you return() from the function somewhere inside the try block (or in the catch block).

I frequently return from functions inside try blocks; it seems neat.

Mark

This topic is closed to new replies.

Advertisement