What is exception chaining in PHP and why is it useful? PHP में exception chaining क्या है और यह क्यों उपयोगी है?
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
}| Benefit | Why it matters |
|---|---|
| Preserves root cause | getPrevious() gives you the original low-level error for debugging |
| Clean abstraction | Calling code only needs to catch OrderProcessingException, not know about PDOException internals |
| Full trace in logs | Log::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 देता है |
| साफ abstraction | Calling 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?