6

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 Answers 3

7

You're looking for the function 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)

Sign up to request clarification or add additional context in comments.

2 Comments

In going off what @svens said, error suppression for turning off all errors is done with error_reporting(0) See us.php.net/manual/en/…
.. 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 :).
5

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();
}

1 Comment

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.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.