php, using a try and catch on warning

hi,
i am trying to catch a warning that occurs when a book has not been found, but i am having problems catching a warning, how can this be done?

       try{
              $response = file_get_contents($bookurl); // get the data
       }
       catch(Exception $e){
        echo $e->getMessage();      
       }

Open in new window


thanks in advance guys
MK15Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

designatedinitializerCommented:
see example.1 in here:
http://pt2.php.net/manual/en/class.errorexception.php

The problem is
Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.

-- in PHP Manual
animecycCommented:
The code you presented while in theory should work, would not because the "file_get_contents" function does not throw an exception, it merely returns FALSE if there is an error. However, you can force it to throw an error if the response is FALSE. For instance:

try {
    if(! $response = file_get_contents($bookurl)) {
        throw new Exception("File could not be opened.");
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ray PaseurCommented:
animecyc has the right answer if you really want a try/catch sequence, but why not just use the @ to suppress function messages.  The return from file_get_contents() will be FALSE if it fails.
if (!$response = @file_get_contents($bookurl)) echo "Oops.  I cannot find $bookurl.";

Open in new window

See http://php.net/manual/en/function.file-get-contents.php to learn the return values from the function.

Sidebar note... You might consider using file_exists() instead of letting file_get_contents() try and fail.  It might be faster.  Not sure of that, but my instincts tell me so.  

Best regards, ~Ray
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

designatedinitializerCommented:
You'll be better off by using set_error_handler, like I mentioned in my 1st answer.
This will throw an exception on every NOTICE:
<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();
?>

Open in new window

Ray PaseurCommented:
Please see http://www.laprbass.com/RAY_temp_designatedinitializer.php
<?php // RAY_temp_designatedinitializer.php

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/* Trigger exception */
strpos();

Open in new window

Outputs:
Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' in /home/websitet/public_html/RAY_temp_designatedinitializer.php:9 Stack trace: #0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/websitet/...', 9, Array) #1 /home/websitet/public_html/RAY_temp_designatedinitializer.php(9): strpos() #2 {main} thrown in /home/websitet/public_html/RAY_temp_designatedinitializer.php on line 9

Maybe this adds value for someone, but I sure don't see it!

Best to all, over and out, ~Ray
designatedinitializerCommented:
I believe the question asked for a way to get the try---catch construct to work.
Try this and you'll see it works as requested.
Try it once, then comment out the 'set_error_handler' and try again...
<?php
// define an error handler function
// this will catch every error, regardless of error level
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

/*
blah blah blah...
*/

$bookurl = "somefilethatdoesntexist";
try{
    $response = file_get_contents($bookurl); // get the data
}catch(Exception $e){
    echo "This error stuff works, regardless of naysayers: ";
    echo $e->getMessage();    
}
?>

Open in new window


This is well explained in the PHP manual page to which I posted the URL in the first place. The value it adds is readily recognizable by any programmer. Exceptions should be treated as such. If you want to close your eyes and silently ignore the errors, then you have the @ facility.
Best of luck with that...
animecycCommented:
While I agree with the above comment, it does take the posed question to an extreme. The answer I provided gives the quickest solution to the question. Unless you are looking to stylize, make errors more human readable, and/or prevent the script from halting setting the global error_handler doesn't make sense.

Also, utilizing PHP's native error handlers in my opinion is better and much more streamlined. If a method was not meant to throw an exception, I don't believe it should be forced to unless necessary. It just simply adds more weight to the application.

If you agree with the above statement, but still want to style your exceptions, take a look at the set_exception_handler function. This will allow for PHP's natural (or user-created) Exceptions to be stylized, and will also stop the execution of the script; To me, especially in critical applications, having to handle the halting of the script in every instance can start to become tedious.

This isn't to say I don't use the above interpretation, I do, it just does not apply to this situation.
designatedinitializerCommented:
@animecyc: you are right, though the matter is debatable. I wouldn't call 4 lines of code "more weight", and the processing time penalty is negligeable. Furthermore, many of the problems people come in here with are due to silent errors, which can be caught by a properly constructed error handler.

Anyway, my previous post was simply meant to clarify what I was talking about, as it seems Ray didn't quite get it...
MK15Author Commented:
thanks a lot guys.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.