Bird
0
0

You want to ensure a file is always closed after reading, even if an exception occurs. Which code snippet correctly uses finally to do this?

hard📝 Application Q8 of 15
PHP - Error and Exception Handling
You want to ensure a file is always closed after reading, even if an exception occurs. Which code snippet correctly uses finally to do this?
Atry { $file = fopen('data.txt', 'r'); /* read */ } catch (Exception $e) { /* handle */ } finally { fclose($file); }
Btry { $file = fopen('data.txt', 'r'); /* read */ } finally { fclose($file); } catch (Exception $e) { /* handle */ }
Ctry { $file = fopen('data.txt', 'r'); /* read */ } catch (Exception $e) { fclose($file); }
Dtry { $file = fopen('data.txt', 'r'); /* read */ } catch (Exception $e) { /* handle */ }
Step-by-Step Solution
Solution:
  1. Step 1: Confirm finally block placement

    finally must come after catch to guarantee execution.
  2. Step 2: Check resource cleanup

    Closing file in finally ensures it runs whether exception occurs or not.
  3. Final Answer:

    try { $file = fopen('data.txt', 'r'); /* read */ } catch (Exception $e) { /* handle */ } finally { fclose($file); } -> Option A
  4. Quick Check:

    finally used for cleanup after try/catch [OK]
Quick Trick: Use finally for cleanup after try/catch [OK]
Common Mistakes:
  • Placing finally before catch
  • Closing file only in catch
  • Not closing file at all

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes