Bird
0
0

How can you ensure that cleanup code runs whether or not an exception occurs in C#?

hard🚀 Application Q9 of 15
C Sharp (C#) - Exception Handling
How can you ensure that cleanup code runs whether or not an exception occurs in C#?
APut cleanup code only in the try block
BPlace cleanup code inside a finally block
CUse catch block for cleanup only
DIgnore cleanup if exception occurs
Step-by-Step Solution
Solution:
  1. Step 1: Purpose of finally block

    The finally block runs after try and catch blocks regardless of exceptions.
  2. Step 2: Using finally for cleanup

    Placing cleanup code in finally ensures it always executes, even if exceptions occur.
  3. Final Answer:

    Place cleanup code inside a finally block -> Option B
  4. Quick Check:

    Cleanup code placement = A [OK]
Quick Trick: Use finally block for guaranteed cleanup code execution [OK]
Common Mistakes:
MISTAKES
  • Putting cleanup only in try block
  • Using catch block alone for cleanup
  • Skipping cleanup on exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More C Sharp (C#) Quizzes