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
Explain exceptions to me :)
Moderator: General Moderators
- daedalus__
- DevNet Resident
- Posts: 1925
- Joined: Thu Feb 09, 2006 4:52 pm
-
jamiel
- Forum Contributor
- Posts: 276
- Joined: Wed Feb 22, 2006 5:17 am
- Location: London, United Kingdom
The Exception class is a built-in PHP Class.
getMessage is a method in the Exception class which returns the first paramater you pass to Exception. (In this case mysql_error()).
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();
}I learnt everything I know about exceptions here: http://www.zend.com/php5/articles/php5-exceptions.php
A snippet from one of my classes:
Then when used..
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
}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');
}- feyd
- Neighborhood Spidermoddy
- Posts: 31559
- Joined: Mon Mar 29, 2004 3:24 pm
- Location: Bothell, Washington, USA
viewtopic.php?t=50490 may be of interest.