C#.NET — Is all code in a finally block guaranteed to run, regardless of whether an exception occurs in the associated try block?

Difficulty: Easy

Correct Answer: True

Explanation:


Introduction / Context:
The finally block in C#.NET is used for cleanup tasks such as releasing resources, closing files, or resetting state. This question checks your understanding of the execution guarantees provided by finally.



Given Data / Assumptions:

  • We have a try block that may or may not throw.
  • A finally block is associated with that try (with or without catch).
  • No explicit process-terminating calls are made (such as Environment.FailFast).


Concept / Approach:
In .NET, the finally block is designed to run after the try (and any catch) completes, regardless of whether an exception was thrown. The runtime ensures that control flows through finally before the method returns or the exception continues to unwind. Only catastrophic conditions that abort the process or thread can prevent finally from running.



Step-by-Step Solution:

If no exception: finally runs after try completes.If an exception is thrown and caught: finally runs after catch.If an exception is thrown and not caught in this method: finally runs during stack unwinding.


Verification / Alternative check:
Instrument code with Console.WriteLine in try, catch, and finally. Observe that finally executes even when an exception is thrown, provided the process is not forcibly terminated.



Why Other Options Are Wrong:
Answer False would imply finally is optional or conditional, which contradicts the language/runtime semantics except in catastrophic cases.



Common Pitfalls:
Assuming finally runs even after Environment.FailFast, process kill, or power loss. These scenarios bypass normal runtime guarantees.



Final Answer:
True

More Questions from Exception Handling

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion