Jump to content
Larry Ullman's Book Forums

Exception Handling For Flow Control?


Recommended Posts

Hi,

 

I have been looking a bit more indepth in regards to exception handling and I stumbled across this idea of using exceptions for flow control. What I am confused about is what actually defines flow control?

 

The best information I could find was:

http://ciaweb.net/pear-exception-use-guidelines.html#toc26

 

Yet, it is still a little sparse on complete detail. After reading about appropriate usage of exceptions I have come to think that perhaps it is incorrect to use them for handling forms? I'm a little confused as to when it is and isn't appropriate to use them.

 

Say I have a login form which is validated and sanitized by an object. If one of the form values is invalid should I use an exception?

 

Thanks,

 

Sam

Link to comment
Share on other sites

It depends. More often than not, application breaking errors should throw exception. As an example, an invalid date, improper email addresses or bad zip codes could benefit from throwing exceptions. The reason for that is data integrity. A class/function could very well be dependent of having valid data on a special format to be able to perform actions/calculations of it.

 

You'll often see people defining their own exceptions like so. In this example we have a example class for sending email. It's no point sending an email to "111lol!", so then it's good practice to throw an exception. (

 

class Email
{
public function send( $email )
{
   if (! filter_var($email, FILTER_VALIDATE_EMAIL))
   {
    throw new InvalidEmailAddressException("Invalid email adress provided.");
   }
}

// Email exception
class InvalidEmailAddressException extends Exception
{
   public function __construct($message) { parent::__construct($message); }
}

 

Hope that gives you a general idea. Short answer would be this: for "checking values", use return values. User::add() could return true/false on how the adding went. For invalid values that could break classes/methods, throw exceptions.

  • Upvote 3
Link to comment
Share on other sites

 Share

×
×
  • Create New...