Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Error & Exception Handling
Interview question

Does the finally block always execute? What are the exceptions to this rule? क्या finally block हमेशा चलता है? इसके अपवाद क्या हैं?

Answer

The finally block runs in almost all cases - after normal completion, after a caught exception, after an uncaught exception propagates further, and even if try/catch contains a return statement.

ScenarioDoes finally run?
Try block completes normallyYes
Exception thrown and caughtYes
Exception thrown and NOT caught (propagates up)Yes, then the exception continues to propagate
return statement inside try or catchYes, finally runs before the function actually returns
exit() or die() called inside tryNo, finally is skipped - the script terminates immediately
Fatal PHP error (e.g. out of memory)No, script terminates immediately

Interview tip: The exit()/die() case is the detail that separates a strong answer from a memorized one - always mention it.

finally block लगभग हर स्थिति में चलता है - normal completion के बाद, caught exception के बाद, uncaught exception आगे propagate होने पर, और try/catch में return statement हो तब भी।

स्थितिक्या finally चलता है?
Try block normally completeहाँ
Exception throw और catch हुआहाँ
Exception throw पर catch नहीं हुआ (आगे propagate)हाँ, फिर exception आगे propagate होता रहता है
try या catch के अंदर return statementहाँ, function असल में return होने से पहले finally चलता है
try के अंदर exit() या die() callनहीं, finally skip हो जाता है - स्क्रिप्ट तुरंत terminate
Fatal PHP error (जैसे out of memory)नहीं, स्क्रिप्ट तुरंत terminate

इंटरव्यू टिप: exit()/die() वाला केस वो डिटेल है जो एक मजबूत जवाब को याद किए हुए जवाब से अलग करता है - हमेशा इसका ज़िक्र करें।

Was this answer clear?