Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.
class Ex_User extends Exception
{
public function __construct($message)
{
parent::__construct($msg);
}
}
try
{
//
}
catch (Ex_MySQL $e)
{
//
}
catch (Ex_User $e)
{
$msg = $e->getMessage(); // Display this msg in the html page as an error message to the user
}
catch (Exception $e)
{
//
}
But I remembered that Exception stores filename and linenumber and has stack tracing routines etc, exceptions are mainly designed for development errors, not for html-form messages.
Is it a bad idea to use an Exception for this purpose ?
Although it's feasible to pop the error message into an exception it may be a little to abrupt. What if the user filled in more than one field incorrectly for example? Another way people deal with this is to setError($field, $message) in the $request object (or somewhere else that makes sense). Then you can just check if $request->hasErrors(), display them.
I'm more of the philosophy that "Exceptions should be EXCEPTIONAL!" Does that make sense?
I use exceptions a fair amount but those exception rarely if ever get thrown. And when they do, there is something very wrong going on like a database server is down or the OS is acting up. Things that I could really care less about the performance hit I'm taking for throwning the exception.
I ONLY use them to catch programming problems, not user error problems. They do come with quite a bit of overhead. And if your using them to catch user mistakes and forget to catch one, your user is left looking at a really ugly mess they should never have been exposed to.
Also as pointed out, you can paint yourself into a corner with exceptions if you need to keep track of multiple errors the user might have caused.
What's nice about exceptions, however, is how they rewind the execution stack, when you otherwise would have needed to bubble up the error with special return values, etc. User errors, however, often change the execution flow of the program, so you need tight integration between the model and controller in these cases.