php:try-catch没有捕获所有异常 [英] php: try-catch not catching all exceptions

查看:324
本文介绍了php:try-catch没有捕获所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作:

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

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

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.

但是,这样的错误不会被'catch'-statement,但是由全局错误处理程序。
然后脚本继续。

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

有没有办法?我只是认为这样做会更加干净,而不是手动类型检查每个变量,这似乎无效,考虑到99%的所有情况都没有发生什么。

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



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

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");



解决方案#2



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

这篇关于php:try-catch没有捕获所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆