Exceptions are often overlooked because of the extra setup you need to do in order to create a good design even though I myself am not a guru of any object oriented design principles. Nevertheless, a programmer should take advantage of its capabilities.
Here is a simple way of using an extended exception in php.
$franz = 'alien';
try{
if($franz != 'human'){
throw new My_Extended_Exception('Error, you are not a human. Go back to your planet', 306);
}
} catch (Exception $e) {
echo $e->logError()->outputError();
}
The neat part with extending an exception is you can play with the class and do your own logging. As an example.
class My_Extended_Exception extends Exception
{
protected $_errorMessage;
public function __construct($message, $code)
{
parent::__construct($message, $code);
}
public function logError()
{
$this->_errorMessage = $this->message . ' code:' . $this->code . ' on line: ' . $this->getLine() . ' in file: ' . $this->getFile() . PHP_EOL;
file_put_contents("errors.txt", $this->_errorMessage,
FILE_APPEND | LOCK_EX
); return $this;
}
// sends the error to the browser;
public function outputError()
{
if($this->_errorMessage){
return $this->_errorMessage;
}
}
}
A little about the code. By extending our exception we added a little ability to log our error messages then also output it to the browser. We basically automate the process and should have control on our errors.
Another big plus using an exception is the native methods of the error class. Here I used 2 which is getLine() and getFile(). Pretty self explanatory which will get the line number of the error and also the file where it came from. There are more of these methods in php.net documentation. I also passed the $message and $code argument to the parent class which is Exception in order to access the message and code property directly (eg: $this->message).
And thats it! hope it helped some.