Bird
0
0

You want to ensure a file stream is always closed after use, even if an exception occurs. Which code pattern correctly uses finally to achieve this?

hard🚀 Application Q8 of 15
C Sharp (C#) - Exception Handling
You want to ensure a file stream is always closed after use, even if an exception occurs. Which code pattern correctly uses finally to achieve this?
Atry { FileStream fs = new FileStream("file.txt", FileMode.Open); // read file } finally { // do nothing }
Btry { FileStream fs = new FileStream("file.txt", FileMode.Open); // read file } catch { fs.Close(); }
CFileStream fs = new FileStream("file.txt", FileMode.Open); try { // read file } finally { fs.Close(); }
DFileStream fs = new FileStream("file.txt", FileMode.Open); try { // read file } catch { fs.Close(); }
Step-by-Step Solution
Solution:
  1. Step 1: Identify where to close the file

    File must be closed regardless of exceptions, so use finally.
  2. Step 2: Check code correctness

    FileStream fs = new FileStream("file.txt", FileMode.Open); try { // read file } finally { fs.Close(); } creates file stream outside try and closes it in finally, ensuring closure.
  3. Final Answer:

    FileStream fs = new FileStream("file.txt", FileMode.Open); try { // read file } finally { fs.Close(); } -> Option C
  4. Quick Check:

    finally ensures cleanup = C [OK]
Quick Trick: Use finally to close resources always [OK]
Common Mistakes:
MISTAKES
  • Closing resource only in catch
  • Not closing resource at all
  • Creating resource inside try but closing outside

Want More Practice?

15+ quiz questions · All difficulty levels · Free

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