87

I'm trying to do the following:

try {
    // just an example
    $time      = 'wrong datatype';
    $timestamp = date("Y-m-d H:i:s", $time);
} catch (Exception $e) {
    return false;
}
// database activity here

In short: I initialize some variables to be put in the database. If the initialization fails for whatever reason - e.g. because $time is not the expected format - I want the method to return false and not input wrong data into the database.

However, errors like this are not caught by the 'catch'-statement, but by the global error handler. And then the script continues.

Is there a way around this? I just thought it would be cleaner to do it like this instead of manually typechecking every variable, which seems ineffective considering that in 99% of all cases nothing bad happens.

1
  • 3
    That's because exceptions are not universally implemented in PHP. They are a PHP5 addition, and very few of the built-in functions will throw them. Instead, you will need to verify the return values of most functions. Mar 17, 2013 at 14:07

5 Answers 5

140
try {
  // call a success/error/progress handler
} catch (\Throwable $e) { // For PHP 7
  // handle $e
} catch (\Exception $e) { // For PHP 5
  // handle $e
}
3
55

Solution #1

Use ErrorException to turn errors into exceptions to handle:

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

Solution #2

try {
    // just an example
    $time      = 'wrong datatype';
    if (false === $timestamp = date("Y-m-d H:i:s", $time)) {
        throw new Exception('date error');
    }
} catch (Exception $e) {
    return false;
}
7
  • 5
    A couple notes: 1) If it's not desired to universally raise exceptions in place of errors throughout the application, this can be enabled where desired and regular error handling can be restored with restore_error_handler(). 2) I expect #2 to still throw a warning. Same concept applies: the error reporting level could be changed with error_reporting() and changed back afterward.
    – Wiseguy
    Mar 17, 2013 at 14:23
  • 2
    The warning MUST BE threw anyway. They are information that you must save it somewhere. If you do not want to see it, just turn off error_display
    – Federkun
    Mar 17, 2013 at 14:27
  • 1
    Solution #2 is how Js does it... it's good if you know what you're doing
    – Ray Foss
    Feb 3, 2018 at 19:51
  • 1
    Follow up question: Is it good idea to use solution #1 in your MVC applications? I feel using it globally defeats the purpose of Exceptions while repeatedly using restore_error_handler() feels very hackish.
    – user2286243
    Mar 19, 2018 at 12:50
  • 1
    Only on debug mode @VarunAgrawal, during the developement. I'd not relay on a global php setting to handle correctly how your application will in fact run in the end.
    – Federkun
    Mar 20, 2018 at 20:50
12

The shorter that I have found:

set_error_handler(function($errno, $errstr, $errfile, $errline ){
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});

Makes all errors becoming instance of catchable ErrorException

12

It is possible to use catch(Throwable $e) to catch all exceptions and errors like so:

catch ( Throwable $e){
    $msg = $e->getMessage();
}
0
7

It's also possible to define multiple types for the $e parameter in catch:

try {
    // just an example
    $time      = 'wrong datatype';
    $timestamp = date("Y-m-d H:i:s", $time);
} catch (Exception|TypeError $e) {
    return false;
}
1
  • Note to readers: this syntax works only for PHP 7.1 and later. "As of PHP 7.1.0, a catch block may specify multiple exceptions using the pipe (|) character. This is useful for when different exceptions from different class hierarchies are handled the same." Sep 6 at 7:35

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.