[SOLVED] PHP5 Exceptions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

[SOLVED] PHP5 Exceptions

Post by partiallynothing »

I believed I understood exceptions, but I guess I was wrong :). I wrote a short script that connects to a database. In the database code, there are Exceptions, which should filter to the error class. The odd thing is, it DOES work. When an error occurs, the error class pickes up the thrown exception and outputs:

Code: Select all

Error 'could not query database' in class 'database' in function 'execute'
The thing is, I also recieve a fatal error:

Code: Select all

Fatal error: Exceptions must be valid objects derived from the Exception base class in /www/openhelp.org/beta/lib_classes.php on line 55
Obviously, I want to get rid of this fatal error. Here is my index page (which calls the database class ):

Code: Select all

<?php
/*----------------------------------------------------------------------------*/
/*OpenHelp                                                                    */
/*Index Page - index.php                                                      */
/*                                                                            */
/*Written by Rob Frawley on 2004-05-06                                        */
/*Last Edited on 2004-07-02                                                   */
/*----------------------------------------------------------------------------*/

/*INCLUDE FILES---------------------------------------------------------------*/

require_once('conf_vars.php');
require_once('lib_classes.php');

/*DEFINE CURRENT PAGE---------------------------------------------------------*/

if (!$_GET['page']) {
  $page_current = 'main';
} else {
  $page_current = strip_tags(htmlspecialchars($_GET['page']));
}

/*MAKE PAGE-------------------------------------------------------------------*/

$database = new database($_CONFIG['db_user'],
                         $_CONFIG['db_pass'],
                         $_CONFIG['db_host'],
                         $_CONFIG['db_name']);
$database->execute('this');

?>
Next is my lib_classes.php file, which includes the database and error class:

Code: Select all

<?php
<?php
/*----------------------------------------------------------------------------*/
/*OpenHelp                                                                    */
/*Class Library - lib_classes.php                                             */
/*                                                                            */
/*Written by Rob Frawley on 2004-05-06                                        */
/*Last Edited on 2004-07-02                                                   */
/*----------------------------------------------------------------------------*/

/*PAGE CLASS------------------------------------------------------------------*/

class page_default {

}

/*DATABASE CLASS--------------------------------------------------------------*/

class database {

  protected $db_user;
  protected $db_pass;
  protected $db_host;
  protected $db_name;
  protected $dbh;

  public function __construct ($db_user, $db_pass, $db_host, $db_name) {
    $this->db_user = $db_user;
    $this->db_pass = $db_pass;
    $this->db_host = $db_host;
    $this->db_name = $db_name;
  }

  protected function connect() {
    $this->dbh = mysql_pconnect ($this->db_host, $this->db_user, $this->db_pass);
    if (!is_resource($this->dbh)) {
      throw new error (__CLASS__, 
                       __FUNCTION__, 
                       'database connection not a valid resource');
    }
    if (!mysql_select_db($this->db_name, $this->dbh)) {
      throw new error (__CLASS__, 
                       __FUNCTION__, 
                       'could not select database');
    }
  }

  public function execute($query) {
    if (!$this->dbh) {
      $this->connect();
    }
    $result = mysql_query($query, $this->dbh);
    if (!$result) {
      throw new error (__CLASS__, 
                       __FUNCTION__, 
                       'could not query database');
    }
    else if (!is_resource($result)) {
      throw new error (__CLASS__, 
                       __FUNCTION__, 
                       'database result is not a valid resource');
    } else {
      return $result;
    }
  }

  public function get_row($result) {
    return mysql_fetcg_row($result);
  }

  public function get_assoc($result) {
    return mysql_fetch_assoc($result);
  }

  public function get_array($result) {
    return mysql_fetch_array($result);
  }
}

/*ERROR CLASS-----------------------------------------------------------------*/

class error {

  public function __construct ($error_class, $error_function, $error_msg) {
    if (!$error_class) {
      $error_class = 'Undefined';
    }
    if (!$error_function) {
      $error_function = 'Undefined';
    }
    if (!$error_msg) {
      $error_msg = 'Undefined';
    }
    echo '<p>Error '''.$error_msg.''' in class '''.$error_class.''' in function '''.$error_function.'''</p>';
  }
}
?>

?>
Any help would be great! Thanks!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

have you tried the following?

Code: Select all

class error extends Exception {
//.....
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Didn't Work...

Post by partiallynothing »

When I changed:

Code: Select all

<?php
class error {
//.....
?>
to:

Code: Select all

<?php
class error extends Exception {
//....
?>
I recieved

Code: Select all

Error 'could not query database' in class 'database' in function 'execute'

Fatal error: Uncaught exception 'error' in /www/openhelp.org/beta/lib_classes.php:53 Stack trace: #0 /www/openhelp.org/beta/index.php(29): database-&gt;execute('this') #1 &#123;main&#125; thrown in /www/openhelp.org/beta/lib_classes.php on line 53
Again, it worked, but I still recieved an fatal error...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

well.. generally.. you need try{...}catch(...){...} blocks for catching exceptions in other languages.. so I'd assume the same for this too..
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Post by partiallynothing »

Hm, I *have* heard of that, but I am unsure how to incorperatre that into my code; could anyone provide an example? Thanks!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

Post by partiallynothing »

Hm, the exceptions explanation on that page was worse than sparse... Could someone please provide an example <em>with my code</em>? Thanks a bunch!
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Code: Select all

<?php 
/*----------------------------------------------------------------------------*/ 
/*OpenHelp                                                                    */ 
/*Index Page - index.php                                                      */ 
/*                                                                            */ 
/*Written by Rob Frawley on 2004-05-06                                        */ 
/*Last Edited on 2004-07-02                                                   */ 
/*----------------------------------------------------------------------------*/ 

/*INCLUDE FILES---------------------------------------------------------------*/ 

require_once('conf_vars.php'); 
require_once('lib_classes.php'); 

/*DEFINE CURRENT PAGE---------------------------------------------------------*/ 

if (!$_GET['page']) { 
  $page_current = 'main'; 
} else { 
  $page_current = strip_tags(htmlspecialchars($_GET['page'])); 
} 

/*MAKE PAGE-------------------------------------------------------------------*/ 

try
{
$database = new database($_CONFIG['db_user'], 
                         $_CONFIG['db_pass'], 
                         $_CONFIG['db_host'], 
                         $_CONFIG['db_name']); 
$database->execute('this');
}
catch(error $e)
{
  print_r($e);
}

?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

small note.. you aren't supposed to echo anything inside the error handling class, generally. It's supposed to be handled by your catch()
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Here is an example which may help?

Code: Select all

<?php
class RSSException extends Exception
{

  private $clsname;
  private $funcname;
  private $feed;
  protected $message;

  function __construct($class, $function, $feed, $message)
  {
    $this->feed = $feed;
    $this->clsname = $class;
    $this->funcname = $function;
    $this->message = $message;
  }

  function getClsname()
  {
    return $this->clsname;
  }
   
  function getFuncname()
  {
    return $this->funcname;
  }
   
  function getFeed()
  {
    return $this->feed;
  }
}


class RSSfeed
{
  function grabRSS($file)
  {
    try
    {
      $feed = $file;
      $contents = array();

      if (!$xml = @simplexml_load_file($feed))
      {
        throw new RSSException(__CLASS__, __FUNCTION__, $feed,
                              'Failed to load RSS feed!');
      }
      
      $contents['channel'] = $xml->channel[0]->title;

      foreach($xml->item as $item)
      {
        $contents['items'][] = $item->title;
      }
    }
    catch (RSSException $e)
    {
      echo "Exception in " . $e->getClsname() . "::" . $e->getFuncname();
      echo ": " . $e->getMessage() . ". Feed name: " . $e->getFeed();
    }
    
    return $contents;
  }
}

$RSS = new RSSfeed();
$contents = $RSS->grabRSS('nonexistant.xml');
?>
User avatar
partiallynothing
Forum Commoner
Posts: 61
Joined: Fri Nov 21, 2003 5:02 pm
Location: connecticut, usa

It worked!

Post by partiallynothing »

Thanks both redmonkey and feyd for your help; I have got my script working!
Post Reply