php:try-catch 没有捕获所有异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15461611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:16:47  来源:igfitidea点击:

php: try-catch not catching all exceptions

phpexceptiontry-catch

提问by Marcos

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.

简而言之:我初始化了一些要放入数据库的变量。如果由于某种原因初始化失败 - 例如因为 $time 不是预期的格式 - 我希望该方法返回 false 并且不会将错误的数据输入到数据库中。

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

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

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% 的所有情况下都没有发生任何不好的事情,这似乎是无效的。

采纳答案by Federkun

Solution #1

解决方案#1

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

回答by Nabi K.A.Z.

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

回答by Luca C.

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

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

回答by Amal Magdy

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

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