Exception or not

Nils Oliver Kröger NO_Kroeger at gmx.de
Mon Mar 3 11:04:50 EST 2008


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hello,

I don't think it is a good pattern because you are kind of mixing
exceptions with return codes which makes the code a lot less readable
later on.

I personally would strongly opt for return codes in this case as one
would intuitively expect a function named validateThisAndThat to return
the result of a validation. This might me a simple true/false, a numeric
code with 0=OK, 1=password not correct, 2=user does not exist or a
string, whatever you need.

In my opinion, such a function should raise an exception if it is unable
to fullfill its task. For example lost connection to user database or
things like that. A function should never propagate an expected result
as an exception.

Greetings Nils

Monica Leko schrieb:
| Suppose you have some HTML forms which you would like to validate.
| Every field can have different errors.  For example, this are the
| forms:
|
| username
| password
| etc
|
| And you want to validate them with some class.  Is this good pattern:
|
| class Foo(object):
| def validateUsername(username):
|   if username isn't correct:
|     raise ValidationError()
| def validatePassword(password):
|   if password isn't correct:
|     raise ValidationError()
|
| code:
| try:
|   usernameError = validateUsername()
| except ValidationError:
|   usernameError = error from exception
| try:
|   passwordError = validatePassword()
| except ValidationError:
|   passwordError = error from exception
|
| So, if there wasn't any errors, usernameError and passwordError both
| contains None, and there was error, both contains some string?  Should
| I use exception or just return None or some string without
| exception?

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFHzCGhzvGJy8WEGTcRAvbGAJoDjn39xCmiOLmkc//0RTfeVXJFTACePRIG
uYoDiQBZwRsShUn60LN/9oQ=
=zvAY
-----END PGP SIGNATURE-----



More information about the Python-list mailing list