[Python-Dev] why string exceptions are bad

Guido van Rossum guido at python.org
Sat Mar 20 16:43:44 EST 2004


> Trying to catch (some, but not all) exceptions from another 
> module can be difficult if the module raises strings.  At
> best, you catch everything, test with == (even though "is" 
> seemed to work in your tests), and maybe reraise.
> 
> If they start raising
> 
> 	"Error:  You requested 7 but the quota is 6"
> 
> you have to regex match.
> 
> If the "same" error is raised several places (or by several
> different modules), there will eventually be a typo.
> 
> 	"Error: That was not a string"
> 	"Error: That was not a string."
> 	"Error: That was mot a string."
> 	"Error  That was not a string."
> 	"Error: That wasn't a string"
> 	"ERROR: That was not a string"
> 
> A class can be defined in a single place (and imported); 
> a typo in the 47th raise statement will show up as a syntax
> error instead of a runtime bug.

There's a serious lack of understanding here of how string exceptions
were supposed to be used originally.

String exceptions are compared by object identity.  This was done by
design to force you to give the exception a name, as in:

  Error = "That was not a string"

  ...

  raise Error

  ...

And in another module:

  try:
      ...
  except mymod.Error:
      ...

In addition, the recommended convention was to use "modname.excname"
for the string, e.g.

  Error = "mymod.Error"

But this is all moot now that they are deprecated.

--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list