try{
...
...
}
catch(Exception e)
{
...
...
}
finally{
Console.WriteLine( " i am inside the finally" );
}
Console.WriteLine( " i am outside the try block" );
[.net] finally clause of C-sharp
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
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".
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.
EDIT: The code in finally will always execute, and it will execute before any code below the finally block executes.
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
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
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.
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
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
Popular Topics
Advertisement