Solved

php, using a try and catch on warning

Posted on 2012-03-30
9
323 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 110

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
Independent Software Vendors: 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!

 
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
 
LVL 110

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

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

751 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