On Sat, Aug 20, 2011 at 1:23 AM, Simon J Welsh <simon@xxxxxxxxxxx> wrote: > On 20/08/2011, at 4:51 PM, Andreas wrote: > > > Hi, > > I wrote stuff with file_put_contents() in a try{} catch{} and it worked. > > > > Then I'd like to check what happens when some error occurs so I > writeprotected the targetfile. > > Instead of getting my own message by the catch{} block I got a standard > warning in the browser. > > > > Can't I catch those warnings, too? > > And why does this function rise a warning when it can't acomplish it's > task? > > > > > > Samplecode: > > try { > > $msg = date ("d.m.Y H:i:s") . 'This should be stored in the > file.'; > > file_put_contents( '/tmp/exceptions.txt', $msg . "\n", > FILE_APPEND); > > } > > catch ( Exception $e ) { > > $msg = "Exception " . $e->getCode() . " / " . $e->getMessage(); > > echo "<p>$msg</p>"; > > } > > file_put_contents() doesn't throw exceptions. As the note on the exception > documentation says: "Internal PHP functions mainly use Error reporting, only > modern Object oriented extensions use exceptions." > > If you look at the documentation for its return value ( > http://php.net/file_put_contents), you'll see that false is returned on > failure. > > In this case, a warning makes more sense than throwing an exception anyway. > A warning can be ignored, either by changing the error_reporting level or > using the error control operator, whereas an exception must be dealt with or > execution halts. > --- > Simon Welsh > Admin of http://simon.geek.nz/ > > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > > Simon explains the rationale and heritage well. If, however, you still wish to catch errors as exceptions, you can do so with code like that below: function error_handler($errno, $errstr, $errfile, $errline) { // must take into account error suppressor (@) and not do anything with them (they equal 0) // http://framework.zend.com/issues/browse/ZF-3829 // check against current error_reporting bitmasks if (!(\error_reporting() & $errno)) { return true; } else { $error_msg = "<dl><dt>Error Type (see http://www.php.net/manual/en/errorfunc.constants.php):</dt><dd>$errno</dd><dt>Error Message:</dt><dd>$errstr</dd><dt>File:</dt><dd>$errfile</dd><dt>Line:</dt><dd>$errline</dd></dl>"; throw new \Exception($error_msg); } } set_error_handler('error_handler'); I just pulled some quick code from my web framework. Adam -- Nephtali: A simple, flexible, fast, and security-focused PHP framework http://nephtaliproject.com