在PHP中,Try Catch无法与require_once一起使用?

38

我不能像这样做吗?

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

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


请检查您的Web服务器日志。那里很可能会有一个PHP错误消息。 - user142162
9
知道了,"require" 不会抛出异常。 - Unicron
3个回答

62

你可以使用 include_once 或者 file_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个字符”)。唉! - Johan
2
不错!但还有一行:if (!file_exsists('/includes/functions.php' )) - Johan
@Johan:再次感谢。希望一切都修好了 :) - a1ex07

10

如您可以在这里所读到的:(强调是我的)

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

6

这个方法应该可以用,但有点取巧。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接