Does the finally block always execute? What are the exceptions to this rule? क्या finally block हमेशा चलता है? इसके अपवाद क्या हैं?
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.
| Scenario | Does finally run? |
|---|---|
| Try block completes normally | Yes |
| Exception thrown and caught | Yes |
| Exception thrown and NOT caught (propagates up) | Yes, then the exception continues to propagate |
| return statement inside try or catch | Yes, finally runs before the function actually returns |
| exit() or die() called inside try | No, 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?