How do you handle multiple exception types in a single catch block? एक ही catch block में कई exception types कैसे handle करें?
PHP allows catching multiple exception types in one catch block using the pipe | separator, avoiding repeated identical catch bodies.
try {
processPayment();
} catch (InsufficientFundsException | CardDeclinedException $e) {
echo 'Payment failed: ' . $e->getMessage();
logPaymentFailure($e);
} catch (Throwable $e) {
echo 'Unexpected error occurred';
logCriticalError($e);
}| Approach | When to use |
|---|---|
| Single catch with | | Multiple exception types need identical handling |
| Multiple separate catch blocks | Each exception type needs different handling logic |
| Catch order | PHP checks catch blocks top to bottom - put more specific exception types before general ones like Throwable |
Interview tip: Mention the catch order rule explicitly - putting a general catch (Throwable) before a specific one makes the specific one unreachable, which is a real bug PHP will not warn you about at compile time in older versions.
PHP एक catch block में pipe | separator से कई exception types catch करने देता है, बार-बार identical catch bodies लिखने से बचाते हुए।
try {
processPayment();
} catch (InsufficientFundsException | CardDeclinedException $e) {
echo 'Payment failed: ' . $e->getMessage();
logPaymentFailure($e);
} catch (Throwable $e) {
echo 'Unexpected error occurred';
logCriticalError($e);
}| तरीका | कब इस्तेमाल करें |
|---|---|
| Single catch with | | कई exception types को identical handling चाहिए |
| अलग-अलग catch blocks | हर exception type को अलग handling logic चाहिए |
| Catch order | PHP catch blocks ऊपर से नीचे चेक करता है - specific exception types को Throwable जैसे general से पहले रखें |
इंटरव्यू टिप: catch order नियम स्पष्ट रूप से बताएं - general catch (Throwable) को specific से पहले रखने पर specific unreachable हो जाता है, यह असली bug है जिसकी warning पुराने versions में compile time पर नहीं मिलती।
Was this answer clear?