Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 337
  • Last Modified:

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
0
MK15
Asked:
MK15
  • 4
  • 2
  • 2
  • +1
1 Solution
 
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
0
 
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

0
 
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
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

0
 
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
0
 
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...
0
 
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.
0
 
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...
0
 
MK15Author Commented:
thanks a lot guys.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now