Subjects

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

How does try-catch-finally work in PHP? PHP में try-catch-finally कैसे काम करता है?

Answer

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);
        }
    }
}
BlockRuns when
tryAlways attempted first
catchOnly if a matching exception type is thrown
finallyAlways, 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?