简体   繁体   English

php:try-catch不能捕获所有异常

[英]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 - eg because $time is not the expected format - I want the method to return false and not input wrong data into the database. 如果初始化由于某种原因而失败(例如,因为$ time不是所需的格式),我希望该方法返回false而不向数据库输入错误的数据。

However, errors like this are not caught by the 'catch'-statement, but by the global error handler. 但是,此类错误不会被“ catch”语句捕获,而会被全局错误处理程序捕获。 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. 我只是认为这样做比使用手动检查每个变量会更干净,考虑到在所有情况下99%都不会发生不良情况,这似乎无效。

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

Solution #1 解决方案1

Use ErrorException to turn errors into exceptions to handle: 使用ErrorException将错误转换为异常以进行处理:

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

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

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 使所有错误成为catchable ErrorException实例

catch(Throwable $e) works catch ( Throwable $e){ $msg = $e-> getMessage(); } catch(Throwable $ e)的工作原理catch ( Throwable $e){ $msg = $e-> getMessage(); } catch ( Throwable $e){ $msg = $e-> getMessage(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM