php: try-catch not catching all exceptions

后端 未结 4 1035
-上瘾入骨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 17:54

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

    0 讨论(0)
  • 2020-12-23 17:56

    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

    0 讨论(0)
  • 2020-12-23 17:59
    try {
      // call a success/error/progress handler
    } catch (\Throwable $e) { // For PHP 7
      // handle $e
    } catch (\Exception $e) { // For PHP 5
      // handle $e
    }
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题