Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try/catch doesn't work in PHP

Tags:

php

try-catch

Why am I getting this error?

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

Here is the code:

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

Aren't try\catch supposed to continue the excecution of the code? Or maybe there is some different way to do it?

like image 720
Victor Marchuk Avatar asked Jul 31 '11 17:07

Victor Marchuk


People also ask

Can we use try catch in PHP?

The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.

Can we use try without catch in PHP?

You must use catch with try . Please look php.net manual. PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP.

What is try catch finally in PHP?

Definition and Usage. The finally keyword is used in try... finally and try... catch... finally structures to run a block of code whether or not an exception occurred.

Which is the correct way to use catch block in PHP?

The “try” block is executed and an exception is thrown if the denominator is zero or negative number. The “catch” block catches the exception and displays the error message. The flowchart below summarizes how our sample code above works for custom types of exceptions.


1 Answers

try... catch is more for null object exceptions and manually thrown exceptions. It really isn't the same paradigm as you might see in Java. Warnings are almost deceptive in the fact that they will specifically ignore try...catch blocks.

To suppress a warning, prefix the method call (or array access) with an @.

 $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.
 }

Oh, and it is best to view Fatal Exceptions are also completely uncatchable. Some of them can be caught in some circumstances, but really, you want to fix fatal errors, you don't want to handle them.

like image 146
cwallenpoole Avatar answered Oct 14 '22 14:10

cwallenpoole