Php: try-catch不捕获所有异常


php: try-catch not catching all exceptions

我想做以下事情:

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

简而言之:我初始化了一些要放在数据库中的变量。如果初始化失败,无论什么原因-例如,因为$time不是预期的格式-我希望该方法返回false,而不是向数据库输入错误的数据。

然而,这样的错误不是由'catch'-语句捕获的,而是由全局错误处理程序捕获的。然后脚本继续。

有办法解决这个问题吗?我只是认为这样做会更干净,而不是手动检查每个变量的类型,这似乎是无效的,考虑到在99%的情况下没有什么不好的事情发生。

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

解决方案#1

使用ErrorException将错误转换为异常来处理:

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

解决方案# 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;
}

我找到的较短的:

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

使所有错误成为可捕获的ErrorException的实例

可以使用catch(Throwable $e)捕获所有异常和错误,如下所示:

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

也可以为catch:

中的$e参数定义多个类型。
try {
    // just an example
    $time      = 'wrong datatype';
    $timestamp = date("Y-m-d H:i:s", $time);
} catch (Exception|TypeError $e) {
    return false;
}