Marcos
Marcos

Reputation: 1195

php: try-catch not catching all exceptions

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.

Upvotes: 95

Views: 100922

Answers (5)

Federkun
Federkun

Reputation: 36934

Note that beside error exceptions PHP has "errors proper" such as Warnings or Notices, which are not exceptions and cannot be caught. If you want to catch them too, use an error handler that converts errors to ErrorException:

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

But you must remember that from now on all Warnings and Notices in the code will become exceptions (and halt the script execution if not caught).

After that you will be able to catch such errors as well:

try {
    // just an example
    echo $nonexistent;
} catch (Throwable $e) {
    echo "Notice level error caught";
}

Upvotes: 57

Luca C.
Luca C.

Reputation: 12574

The shorter that I have found:

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

Makes all errors becoming instance of catchable ErrorException

Upvotes: 12

mikiqex
mikiqex

Reputation: 5303

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

Upvotes: 8

Amal Magdy
Amal Magdy

Reputation: 197

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

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

Upvotes: 14

Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10714

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

Upvotes: 149

Related Questions