Using custom exceptions (Opinions please)

Hi guys,

I’ve been playing with Exceptions recently and wondering if i’ve got the wrong end of the stick with regards to exceptions.

The code below is the basic outline of a user registration I’m working on.
Do you think there are too many exceptions?
When is too much, too much?

// Emails
		try {
			
			if( strlen( $this->_email ) == 0 ){
				throw new user_exception( user_errors::MISSINGINPUT_EMAIL );
			} elseif( !is_valid( 'email' , $this->_email ) ){
				throw new user_exception( user_errors::INVALID_EMAIL );
			} elseif( !is_unique( 'user_email' , $this->_email , 'users' ) ){
				throw new user_exception( user_errors::REGISTERED_EMAIL );
			}
			
		} catch( Exception $e ){
			
			$this->_errors[] = $e->getMessage();
			
		}

		// Username
		try {
			if( strlen( $this->_login_name ) == 0 ){
				throw new user_exception( user_errors::MISSINGINPUT_LOGINNAME );
			}
		} catch( Exception $e ){
			$this->_errors[] = $e->getMessage();
		}

		// Password
		try {
			if( strlen( $this->_password ) == 0 ){
				throw new user_exception( user_errors::MISSINGINPUT_PASSWORD );
			}
		} catch( Exception $e ){
			$this->_errors[] = $e->getMessage();
		}

Cheers.

I think you are muddling Exceptions (exceptional errors that should not really happen) with handling the normal user input errors.

I can say that because that was how it was explained to me, on here - but I am unable to find the thread, something up with the Advanced Search?

This is a good thread http://www.sitepoint.com/forums/showthread.php?626951-Exceptions-When-to-throw-and-when-to-catch&highlight=exception

Hmm… thanks for the reply and link.

I was thinking that Exceptions were for runtime related errors, but there’s been a few articles over the last few months which has made me think twice about them.

I suppose I could create an error handler with similar functionality to Exception and leave Exception soley for more important errors such as runtime and database errors for example.

Cheers.

Unexpected input isnt an Exception - but it can lead to one. Exceptions (generally) are used when an external process throws a failure that could not be predictively caught.

For example, from your code…


        try {
            if( strlen( $this->_login_name ) == 0 ){
                throw new user_exception( user_errors::MISSINGINPUT_LOGINNAME );
            }
        } catch( Exception $e ){
            $this->_errors[] = $e->getMessage();
        }

You’re running a simple IF. The IF will never FAIL or throw an error, it will just evaluate it’s condition to true or false (returning false is NOT an error). So there’s no need to try/catch this.

 if( strlen( $this->_login_name ) == 0 ){
            $this->_errors[] = user_errors::MISSINGINPUT_LOGINNAME;
        }

Giod point. I must have been having a really bad day lol. However there’s an article on nettuts about exceptions and that is where I got this confusion from.