QA
Intermediate LevelPHP 8+

How do you convert legacy PHP warnings and notices into fatal exceptions using set_error_handler()?

❓ Interview Prompt: Explain set_error_handler(), ErrorException, converting E_WARNING / E_NOTICE into catchable exceptions, and error_reporting bitmasks.

Legacy PHP functions often emit non-fatal 'E_WARNING' or 'E_NOTICE' errors (like 'file_get_contents()' failing or missing array keys) instead of throwing exceptions. Silent warnings can pass unhandled, causing downstream bugs.

Converting Warnings to Exceptions:

Use 'set_error_handler()' to register a custom error handler callback that wraps all PHP notices and warnings in an 'ErrorException', allowing them to be caught cleanly inside standard 'try/catch' blocks!

Code Implementation Example

php
<?php
// Convert all PHP Notices, Warnings, and Errors into ErrorException!
set_error_handler(function (int $severity, string $message, string $file, int $line): void {
    if (!(error_reporting() & $severity)) {
        return; // Respect error_reporting settings
    }
    throw new ErrorException($message, 0, $severity, $file, $line);
});

try {
    // Attempt to open missing file (normally emits silent E_WARNING)
    $content = file_get_contents('missing_file.txt');
} catch (ErrorException $e) {
    echo "Successfully caught warning as Exception: " . $e->getMessage();
}
💡Converting legacy PHP warnings into catchable ErrorException instances using set_error_handler.
🎯 Interview Key Takeaway

Use set_error_handler() to throw ErrorException on warnings and notices, unifying error handling under try/catch blocks.

#set_error_handler#ErrorException#Error Handling#Intermediate
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?