views:

79

answers:

3

How can I know during runtime that my code threw a Warning?

example

try {
    echo (25/0);
} catch (exception $exc) {
    echo "exception catched";
}

throws a "Warning: Division by zero" error that i can not handle on my code.

+3  A: 

You're looking for the function set_error_handler(). http://ch.php.net/set_error_handler Check out the sample code in the manual.

Make sure that you don't only suppress the error warnings, but instead silently redirect them to a log file or something similar. (This helps you track down bugs)

svens
In going off what @svens said, error suppression for turning off all errors is done with `error_reporting(0)` See http://us.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting
Levi Hackwith
.. or by prepending an '@' to the command. Btw. the error handler will also be called when error_reporting is set to zero (with errno=0). The error handler is very handy and can be used to do things like final logging of time, parameters, memory usage, etc and notify the admin (for fatal errors). I don't wanted to recommend suppressing errors :).
svens
+4  A: 

You need to handle the exception yourself as follows.e.g

function inverse($x)
{
    if(!$x)
    {
         throw new Exception('Division by zero.');
    }
    else
    { 
        return 1/$x;
    }
}


try
{
     echo inverse(5);
     echo inverse(0);
}
catch (Exception $e)
{ 
    echo $e->getMessage();
}
SpawnCxy
you totally misunderstood how exceptions work
stereofrog
@stereofrog,thanks for the note.I'm trying to make it clear.
SpawnCxy
the purpose of exceptions is not to "prevent" errors from happening, like you do, but to provide a way of handling them _when_ they happen. Still, +1 for trying.
stereofrog
+1  A: 

You need to install an error handler that converts old style php "errors" into exceptions. See an example here

stereofrog