How does try-catch-finally work in PHP? PHP में try-catch-finally कैसे काम करता है?
The try block contains code that might fail. The catch block handles the exception if one is thrown. The finally block always runs, whether an exception occurred or not - used for cleanup.
function readFile(string $path): string {
$handle = fopen($path, 'r');
try {
if (!$handle) {
throw new RuntimeException('Cannot open file');
}
return fread($handle, filesize($path));
} catch (RuntimeException $e) {
echo 'Error: ' . $e->getMessage();
return '';
} finally {
if ($handle) {
fclose($handle);
}
}
}| Block | Runs when |
|---|---|
| try | Always attempted first |
| catch | Only if a matching exception type is thrown |
| finally | Always, even if there's a return statement or the exception is unhandled |
Interview tip: Emphasize that finally runs even when the try or catch block contains a return statement - a common trick question.
try block में वो कोड होता है जो fail हो सकता है। catch block exception को handle करता है अगर throw हुआ हो। finally block हमेशा चलता है, चाहे exception हुआ हो या नहीं - cleanup के लिए इस्तेमाल होता है।
function readFile(string $path): string {
$handle = fopen($path, 'r');
try {
if (!$handle) {
throw new RuntimeException('Cannot open file');
}
return fread($handle, filesize($path));
} catch (RuntimeException $e) {
echo 'Error: ' . $e->getMessage();
return '';
} finally {
if ($handle) {
fclose($handle);
}
}
}| Block | कब चलता है |
|---|---|
| try | हमेशा पहले attempt होता है |
| catch | सिर्फ matching exception type throw हो तो |
| finally | हमेशा, चाहे return statement हो या exception unhandled हो |
इंटरव्यू टिप: ज़ोर दें कि finally तब भी चलता है जब try या catch block में return statement हो - एक आम ट्रिक सवाल।
Was this answer clear?