[RESOLVED] Try/Catch with File_get_contents

liunx

Guest
I'm not sure if I am using try/catch incorrectly but here is my example,

try{

$xml = file_get_contents("http://www.someotherdomain.com/file.txt");

} catch(Exception $e){

echo "Load Failed\n";

}


The way I see it, try catch is good for this since there is a chance the resource is external and you cant be sure that its accessible. What I don't understand is, why do you still get the "failed to open stream: HTTP request failed!" warning when the code is within the try/catch block

Isn't the try/catch supposed to stop the errors being displayed then go to the catch block. Then you can choose to do what you want with the error message inside the Exception object.

What seems to happen is you get the warning and it goes to the catch...Damn, Seems I messed up in my example testing somehow.

It seems file_get_contents doesn't throw and exception, so try/catch doesn't do anything for it at all. That's quite annoying...Could you do this w/out the exceptions?if(!$xml = file_get_contents('file.txt'))
{
print 'Load Failed.';
}If you really wanted exceptions...function myFetchContents($file)
{
if(!$xml = file_get_contents($file))
{
throw new Exception('Load Failed');
}
}

// to call

try {
myFetchContents('file.txt');
}
catch(Exception $e)
{
print $e->getMessage();
}Of course you can, but that's not really my point. I was playing around and trying out exceptions.

I just find it funny that some errors/fails will trigger an exception and some don't.

file_get_contents returns a warning, but doesn't cause an exception. So, say you use Exception handling for whatever other reason, you then need to do it manually with file_get_contents (among others)I think that's because exception handling was introduced in PHP5 as one of their OOP features. The try/catch is just a complicated if statement, and I don't see much use for it if you're trying to use instead of an if statement. It's much more beneficial if you are using objects that throw exceptions so the client code knows something went wrong, but the object itself doesn't handle how to handle them. They provide substantial debugging information and can really aid in an object-oriented environment.
 
Back
Top