I’m trying to figure out what exceptions should be used for; logging application errors, or displaying user errors, and if both, how should I distinguish between and handle a user error (e.g. failed login) and an application error (e.g. a failure to connect to the database) with exceptions.
For example, let’s say a user attempts to login, but fails (user error):
if(!$user->login($_POST)) {
//$user->login() throws an Exception, throw new Exception("failed login"), on fail.
catch(Exception $e) {
print $e->getMessage();
}
}
Or perhaps a database error occurs (error logging):
public function query($query) {
$this->resource = mysql_query($query) or throw new Exception("Database error:" . mysql_error());
}
Which of the above two examples would be an appropriate use case, if either?
Exceptions are for signalling exceptional behaviour on part of your program. During normal operation, your program should not usually throw exceptions at all. Something like a failed login is a normal result of your login mechanism, not an exception.
[A failed login may be an exception on the user‘s end (if the user had reason to expect the login to work unconditionally)!]
Typical exceptional situations are running out of memory, running out of disk space, an error in the database connection, or an error during reading or writing a file. All those are things that you would normally expect to work, so an error there is an exceptional condition.
See my previous answer for more details.