php: try-catch not catching all exceptions

后端 未结 4 1050
-上瘾入骨i
-上瘾入骨i 2020-12-23 17:34

I\'m trying to do the following:

try {
    // just an example
    $time      = \'wrong datatype\';
    $timestamp = date(\"Y-m-d H:i:s\", $time);
} catch (Ex         


        
4条回答
  •  青春惊慌失措
    2020-12-23 18:00

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

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

提交回复
热议问题