-2

How to skip finally block in C#?

Is it possible to skip the 'finally' block even though its present after a try And catch block.

  • It may be possible to effectively skip it by use of a `goto` statement. – STLDev Feb 09 '17 at 07:58
  • 3
    Why would you want to? Or do you have a situation where a finally black seems to have been skipped? Do you have a code example? – SQB Feb 09 '17 at 07:58
  • 1
    There are some catastrophic failures and native exceptions that can not be cought that would cause the finally block not be be executed. Just to state the obvious: Don't use this for control-flow in your program. **Why** do you need to skip the finally block and why don't you just set a boolean somewhere that denotes if it should be executed or not? – Manfred Radlwimmer Feb 09 '17 at 08:00
  • The problem is: what do you have in that finally block that needs to be executed conditionally? And why you have it there? – Steve Feb 09 '17 at 08:00
  • actually interviewer ask this question – Rajvardhan Babar Feb 09 '17 at 08:01
  • 1
    See marked duplicate, as well as _that_ post's marked duplicate. Under normal circumstances, the answer is "yes, finally always executes", but there are caveats. Addressed adequately in those two posts, as well as references linked by answers in those pages. – Peter Duniho Feb 09 '17 at 08:04
  • See also this very useful answer: http://stackoverflow.com/a/10260233/3538012 – Peter Duniho Feb 09 '17 at 08:08

1 Answers1

3

The only way I can think of is a flag:

bool skipFinally = false;

try
{
    DoSomething();
    skipFinally = true;
    DoSomethingElse();
}
finally
{
    if (!skipFinally)
        DoFinallyStuff();
}

So the finally block literally gets executed, but you can decide what to do there.


But it has the smell of a design flaw. Why do you have code in a finally block that possibly should not be executed in the first place?
But on the other hand: the C# compiler generates code like above for iterator blocks.

René Vogt
  • 43,056
  • 14
  • 77
  • 99