【问题标题】:Try Catch cannot work with require_once in PHP?Try Catch 不能在 PHP 中使用 require_once?
【发布时间】:2011-03-20 15:42:55
【问题描述】:

我不能这样做吗?

try {
    require_once( '/includes/functions.php' );      
}
catch(Exception $e) {    
    echo "Message : " . $e->getMessage();
    echo "Code : " . $e->getCode();
}

没有回显错误,服务器返回 500。

【问题讨论】:

  • 检查您的网络服务器日志。那里很可能会出现 PHP 错误消息。
  • 仅供参考,require 不会抛出异常。

标签: php


【解决方案1】:

您可以使用include_oncefile_exists

try {
    if (! @include_once( '/includes/functions.php' )) // @ - to suppress warnings, 
    // you can also use error_reporting function for the same purpose which may be a better option
        throw new Exception ('functions.php does not exist');
    // or 
    if (!file_exists('/includes/functions.php' ))
        throw new Exception ('functions.php does not exist');
    else
        require_once('/includes/functions.php' ); 
}
catch(Exception $e) {    
    echo "Message : " . $e->getMessage();
    echo "Code : " . $e->getCode();
}

【讨论】:

  • 试图编辑以纠正 file_exists 的拼写错误,但系统不允许(“编辑必须至少 6 个字符”)。哦!
  • 不错!但仍然有一个: if (!file_exsists('/includes/functions.php' ))
  • @Johan:再次感谢。希望解决一切:)
【解决方案2】:

如您所见 here : (emph mine)

require() 等同于 include() 除非失败,它也会 产生 致命的 E_COMPILE_ERROR 级别 错误。换句话说,它将停止 脚本

这是关于 require 的,但它相当于 require_once()。这不是可捕获的错误。

顺便说一下,你需要输入绝对路径,我觉得这样不对:

 require_once( '/includes/functions.php' ); 

你可能想要这样的东西

require_once( './includes/functions.php' ); 

或者,如果您从子目录或包含在不同目录中的文件调用它,您可能需要类似

require_once( '/var/www/yourPath/includes/functions.php' ); 

【讨论】:

    【解决方案3】:

    这应该可以,但它有点小技巧。

    if(!@include_once("path/to/script.php")) {
        //Logic here
    }
    

    【讨论】:

      猜你喜欢
      • 2012-09-04
      • 2020-01-21
      • 2012-11-25
      • 1970-01-01
      • 1970-01-01
      • 2015-03-31
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多