Subjects

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

What is set_error_handler() and set_exception_handler() in PHP? PHP में set_error_handler() और set_exception_handler() क्या हैं?

Answer

These functions let you override PHP's default handling of errors and uncaught exceptions with your own logic - commonly used to log issues centrally instead of showing raw output.

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    error_log("Error [$errno]: $errstr in $errfile on line $errline");
    return true; // prevents PHP's default handler from also running
});

set_exception_handler(function (Throwable $e) {
    error_log('Uncaught: ' . $e->getMessage());
    http_response_code(500);
    echo 'Something went wrong. Please try again later.';
});
FunctionHandles
set_error_handler()Traditional PHP errors/warnings/notices (E_WARNING, E_NOTICE, etc.)
set_exception_handler()Any exception that was thrown but never caught by your code

Interview tip: Note that frameworks like Laravel already register their own global handlers internally (App\Exceptions\Handler), so in framework code you rarely call these directly - but understanding them is essential for plain PHP and legacy codebases.

ये functions PHP के errors और uncaught exceptions के default handling को अपने logic से override करने देते हैं - आमतौर पर raw output दिखाने के बजाय issues को centrally log करने के लिए इस्तेमाल होते हैं।

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    error_log("Error [$errno]: $errstr in $errfile on line $errline");
    return true; // PHP के default handler को चलने से रोकता है
});

set_exception_handler(function (Throwable $e) {
    error_log('Uncaught: ' . $e->getMessage());
    http_response_code(500);
    echo 'Something went wrong. Please try again later.';
});
Functionक्या handle करता है
set_error_handler()Traditional PHP errors/warnings/notices (E_WARNING, E_NOTICE, आदि)
set_exception_handler()कोई भी exception जो throw हुआ पर आपके कोड ने catch नहीं किया

इंटरव्यू टिप: बताएं Laravel जैसे frameworks पहले से अपने global handlers internally register करते हैं (App\Exceptions\Handler), इसलिए framework code में इन्हें सीधे कम ही call करते हैं - पर plain PHP और legacy codebases के लिए समझना ज़रूरी है।

Was this answer clear?