try/catch在PHP中不起作用

Vic*_*huk 15 php try-catch

为什么我收到此错误?

Warning: file_get_contents(http://www.example.com) [function.file-get-contents]: failed to open stream: HTTP request failed! in C:\xampp\htdocs\test.php on line 22

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\test.php on line 22
Run Code Online (Sandbox Code Playgroud)

这是代码:

 try {
    $sgs = file_get_contents("http://www.example.com");
 }
 catch (Exception $e) {
    echo '123';
 }
 echo '467';
Run Code Online (Sandbox Code Playgroud)

是不是尝试\ catch应该继续执行代码?或者也许有一些不同的方式来做到这一点?

cwa*_*ole 14

try ... catch更多用于空对象异常和手动抛出异常.它实际上与您在Java中看到的范式不同.警告几乎具有欺骗性,因为它们会特别忽略try ... catch块.

要禁止警告,请使用方法调用(或数组访问)作为前缀@.

 $a = array();
 $b = @$a[ 1 ]; // array key does not exist, but there is no error.

 $foo = @file_get_contents( "http://somewhere.com" );
 if( FALSE === $foo ){ 
     // you may want to read on === there;s a lot to cover here. 
     // read has failed.
 }
Run Code Online (Sandbox Code Playgroud)

哦,最好是查看致命异常也完全无法捕获.其中一些可以在某些情况下被捕获,但实际上,您想要修复致命错误,您不想处理它们.


Kar*_*ath 5

catch 无法捕获致命错误。

只需timeout在手册中搜索file_get_contents,那里列出了几种解决方案,这里是一个:

$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1
        )
    )
);
file_get_contents("http://example.com/", 0, $ctx); 
Run Code Online (Sandbox Code Playgroud)