Page 1 of 1

Explain exceptions to me :)

Posted: Thu Jul 27, 2006 2:23 am
by daedalus__
I've been looking at alot of stuff but still don't quite understand the process..

I know I wrap blocks in try { } and then 'catch' exceptions but where are those exceptions defined and how do i throw them?

examples, examples, pretty please with super shooger on top

Posted: Thu Jul 27, 2006 3:53 am
by jamiel
The Exception class is a built-in PHP Class.

Code: Select all

try {
      // Connect to DB
      $db = mysql_connect($host, $user, $pass);

      if (!$db) {
          // Whoops it failed
          throw new Exception(mysql_error());
      }
} catch (Exception $e) {
    // Print error
    print $e->getMessage();
}
getMessage is a method in the Exception class which returns the first paramater you pass to Exception. (In this case mysql_error()).

Posted: Thu Jul 27, 2006 3:56 am
by Oren
I learnt everything I know about exceptions here: http://www.zend.com/php5/articles/php5-exceptions.php

Posted: Thu Jul 27, 2006 5:39 am
by Jenk
A snippet from one of my classes:

Code: Select all

class ConnectionException extends Exception {}
class MySQLException extends Exception {}

class MySQLDatabase extends AbstractDataBase implements iDatabase
{
    public function __construct ($host, $user, $pass, $db = null)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pass = $pass;
        $this->db = $db;
    }

    public function connect()
    {
        $this->resource = @mysql_connect($this->host, $this->user, $this->pass);

        if (!$this->resource) throw new ConnectionException('Could not connect to MySQL Database: ' . mysql_error());

        if (!is_null($this->db)) $db = @mysql_select_db($this->db, $this->resource);

        if (!$db) throw new MySQLException('Database could not be selected: ' . mysql_error());
    }

//snip

}
Then when used..

Code: Select all

include_once 'includes/classes/AbstractDataBase.class.php';
include_once 'includes/classes/MySQLDatabase.class.php';
include_once 'includes/interfaces.inc.php';

try {
    $db = new MySQLDataBase ('host', 'user', 'pass', 'db');
    $db->connect();
} catch (ConnectionException $e) {
    Error::LogError($e->getMessage());
    die ('There has been an error connecting to the Database');
} catch (MySQLException $e) {
    Error::LogError($e->getMessage());
    die ('There has been an error with the MySQL Database');
}

Posted: Thu Jul 27, 2006 9:58 am
by feyd
viewtopic.php?t=50490 may be of interest.