我正在尝试使用PHP中的异常处理。例如,我有一个脚本,它读取一个 $_GET 请求并加载一个文件;如果文件不存在,则应该抛出新的异常:
if ( file_exists( $_SERVER['DOCUMENT_ROOT'] .'/'.$_GET['image'] ) ) {
// Something real amazing happens here.
}
else {
throw new Exception("The requested file does not exists.");
}
问题在于,当我尝试为测试提供一个不存在的文件时,我得到了一个500错误而不是异常信息。服务器日志如下:
[09-Jul-2013 18:26:16 UTC] PHP Fatal error: Uncaught exception 'Exception' with message 'The requested file does not exists.' in C:\sites\wonderfulproject\script.php:40
Stack trace:
#0 {main}
thrown in C:\sites\wonderfulproject\script.php on line 40
我想知道是否有什么非常明显的东西我没注意到。
我已经查看了这个问题:PHP致命错误:未捕获异常'Exception',信息为,但它与我的问题不完全相同,并且没有简洁的答案。
请帮忙吗?
*编辑*
看起来这与throw
关键字有关。例如,如果我使用echo
,我会在屏幕上打印出消息,就像这样:
exception 'Exception' with message 'The file does not exists.' in C:\sites\wonderfulproject\script.php:183 Stack trace: #0 {main}
这是为什么呢?
**编辑2**
感谢@Orangepill,我更好地理解了如何处理异常。我发现一个非常好的教程来自nettuts,对我很有帮助。链接:http://net.tutsplus.com/tutorials/php/the-ins-and-outs-of-php-exceptions/
file_exists
显然返回了false
,很可能是因为该文件实际上不存在。 - deceze