[thelist] catching "Division by Zero" in PHP

Arthur Noel arthur at arthurnoel.com
Wed Nov 14 19:24:08 CST 2001


Jon,

on Thursday, November 15, 2001 12:56:27 AM, you wrote:

> I'm doing some math with php, and I want to detect when a division by
> zero warning occurs, and stop the program outputting a message. Because
> php carries on ignoring the division by zero which cannot be done, the
> result is incorrect. I hope to do this independently on the page, not
> making changes to php.ini.

What you want then is to define your own error handler. Something like this:

function error_handler($error_no, $error_str, $error_file, $error_line) {
        // not for @ errors
        if (error_reporting() == 0) return;
        // sort out what kind of error we have
        switch($error_no) { 
                case E_NOTICE:
                        return;
                        break; 
                case E_USER_NOTICE:
                        $continue = TRUE;        
                        $type = "Notice"; 
                        break;
                case E_USER_WARNING:
                case E_WARNING: 
                        $continue = TRUE;        
                        $type = "Warning"; 
                        break;
                case E_USER_ERROR:
                case E_ERROR:
                        $type = "Fatal Error"; 
                        break;
                default: 
                        $type = "Unknown Error"; 
                        break;
                }
        // put in error log
        error_log("[".date("d-M-Y H:i:s")."] PHP $type: $error_parts[0] error in line $error_line of file $error_file", 0);
        if ($error_str == "Division by zero") { // do your thing
                
                }
        else { // display
                echo "\n<div>".nl2br($error_str)."</div>\n";
                }

        // halt for fatal errors
        if (!isset($continue)) exit();
        }

set_error_handler("error_handler");

One thing to note though is that by setting the
error handler you are bypassing PHP's error handling entirely so you should
make sure that your error handling function is able to handle all errors
thrown at it.

Have a look at
http://www.php.net/manual/en/function.set-error-handler.php which gives an
example too.

Cheers,
Arthur





More information about the thelist mailing list