Exceptions Concept

I have been researching exceptions in PHP 5 in an attempt to create a error handling system for a framework I am working on. I get how they work by throwing them and then catching and such but I think I’m missing something, if anyone can help shed some light that would be great.

I don’t seem to be able to throw exceptions between classes. I have a MySQLi class and I have a User class. There are two ways the User class can be used, either via AMF by a flash/flex interface or just by calling it in PHP from HTML frontend.

This is my scenario:

An instance is created of the User class and in the construct an instance of the MySQLi class is created. In the construct of the MySQLi class a new connection is made to the database. If for some reason the MySQLi class is unable to connect I want to throw an exception and be able to catch it back in the User class so I can return appropriate output. I dont seem to be able to catch it back in the User class though, I just get uncaught exception.

If I’m unable to catch the exception within the MySQLi class I’m not sure how I can notify the User class that there has been an error so it can take approriate action (it needs to be able to return a VO with a success or error status to whatever called it in the first place).

Heres a quick basic example of what I am doing and I dont seem to be able to get it to work.



Class UserService {

	public function __construct()
	{
		//create an instance of the mysqlihandler class
		try {
			$this->mysqliHandler = new MysqliHandler();
		}
		catch(Exception $e) {
			//handle and return an error code to whatever called/created instance of this class
		}
	}
}



Class MysqliHandler{

	private $mysqlHost;
	private $mysqlUser;
	private $mysqlPass;
	private $mysqlDb;

	public function __construct()
	{
		$this->mysqlHost = 'localhost'; // mysql host
		$this->mysqlUser = '#'; // mysql username
		$this->mysqlPass = '#'; // mysql password
		$this->mysqlDb = '#'; // mysql database
		
		//create a new mysqli object/connection
		$this->link = new mysqli($this->mysqlHost, $this->mysqlUser, $this->mysqlPass, $this->mysqlDb);

		//if there is an error connecting, throw an exception
		if($this->link->connect_errno)
		{
			throw new Exception('Some error', 123);
		}
	}
}

I’m pretty sure I’m missing something from my understanding of this so if anyone can help that would be great.

Thanks!

I’m feeling very stupid right now, I think its because I had another class in there too that was create an instance of mysqli class but I didnt have a try and catch block on it so it was running first and getting an uncaught exception error!

Thanks for taking the time to reply.

If I throw an error should the rest of the script stop running? I seem to be having errors kicked out about queries running after the exception is thrown but maybe I’m running them elsewhere.

That all appears to be valid syntax, can you provide an actual error message?