Subjects

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

How do you handle multiple exception types in a single catch block? एक ही catch block में कई exception types कैसे handle करें?

Answer

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);
}
ApproachWhen to use
Single catch with |Multiple exception types need identical handling
Multiple separate catch blocksEach exception type needs different handling logic
Catch orderPHP 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 orderPHP catch blocks ऊपर से नीचे चेक करता है - specific exception types को Throwable जैसे general से पहले रखें

इंटरव्यू टिप: catch order नियम स्पष्ट रूप से बताएं - general catch (Throwable) को specific से पहले रखने पर specific unreachable हो जाता है, यह असली bug है जिसकी warning पुराने versions में compile time पर नहीं मिलती।

Was this answer clear?