Subjects

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

What is exception chaining in PHP and why is it useful? PHP में exception chaining क्या है और यह क्यों उपयोगी है?

Answer

Exception chaining lets you wrap a low-level exception inside a higher-level, more meaningful one while preserving the original cause. PHP's Exception constructor accepts a previous exception as its third argument.

class OrderProcessingException extends Exception {}

try {
    try {
        $pdo->query('INSERT INTO orders ...');
    } catch (PDOException $e) {
        throw new OrderProcessingException(
            'Failed to save order',
            0,
            $e // the original exception, preserved as the "previous" one
        );
    }
} catch (OrderProcessingException $e) {
    echo $e->getMessage();          // 'Failed to save order'
    echo $e->getPrevious()->getMessage(); // original PDOException message
}
BenefitWhy it matters
Preserves root causegetPrevious() gives you the original low-level error for debugging
Clean abstractionCalling code only needs to catch OrderProcessingException, not know about PDOException internals
Full trace in logsLog::error() with an exception object includes the whole chain automatically in most frameworks

Interview tip: This shows senior-level thinking - it demonstrates you understand layered architecture (e.g. repository layer errors shouldn't leak database-specific exceptions to the controller layer).

Exception chaining एक low-level exception को ज़्यादा meaningful high-level exception में wrap करने देता है, original कारण को सुरक्षित रखते हुए। PHP के Exception constructor का तीसरा argument previous exception लेता है।

class OrderProcessingException extends Exception {}

try {
    try {
        $pdo->query('INSERT INTO orders ...');
    } catch (PDOException $e) {
        throw new OrderProcessingException(
            'Failed to save order',
            0,
            $e // original exception, "previous" के रूप में सुरक्षित
        );
    }
} catch (OrderProcessingException $e) {
    echo $e->getMessage();          // 'Failed to save order'
    echo $e->getPrevious()->getMessage(); // original PDOException message
}
फायदाक्यों मायने रखता है
Root cause सुरक्षितgetPrevious() debugging के लिए original low-level error देता है
साफ abstractionCalling code को सिर्फ OrderProcessingException catch करना है, PDOException internals जानने की ज़रूरत नहीं
Logs में पूरा traceअधिकतर frameworks में exception object के साथ Log::error() पूरी chain automatically शामिल करता है

इंटरव्यू टिप: यह senior-level सोच दर्शाता है - यह दिखाता है आप layered architecture समझते हैं (जैसे repository layer errors को controller layer में database-specific exceptions leak नहीं करने चाहिए)।

Was this answer clear?