Solved

php, using a try and catch on warning

Posted on 2012-03-30
9
306 Views
Last Modified: 2012-08-13
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
Comment
Question by:MK15
  • 4
  • 2
  • 2
  • +1
9 Comments
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37789716
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
 
LVL 3

Accepted Solution

by:
animecyc earned 500 total points
ID: 37791559
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
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37793206
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37793256
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 37793289
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37793400
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
 
LVL 3

Expert Comment

by:animecyc
ID: 37793437
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
 
LVL 7

Expert Comment

by:designatedinitializer
ID: 37793483
@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
 

Author Closing Comment

by:MK15
ID: 37819065
thanks a lot guys.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now