How do I know all thrown exceptions of a function?

Donn Cave donn at u.washington.edu
Wed Jan 24 12:32:06 EST 2001


Quoth scarblac at pino.selwerd.nl (Remco Gerlich):
| (Paul)
| | No.  If your code gets, say, a bad value, it should raise ValueError,
| | not some new version of ValueError defined only in that module.
|
| Ah, of course. If there's an obvious builtin exception for exactly this
| problem, use that. That should cover many cases.
|
| My point is though, say you have some markup language parser that is looking
| for an end tag. Your string.index() call fails with a ValueError (end marker
| not found). Now it would be best to catch that and raise some sort of
| mymarkupparser.MissingEndTag exception, not to simply pass on the unhelpful
| ValueError that might change once you switch to regular expressions.

That makes sense to me.  Now we're talking about a basic and obvious
premise:  exceptions allow a function to communicate with its callers.
When it can say something -- "Your input had no end tag" -- then
it should ideally say it in the clearest way.  Good if it's a more
particular exception than ValueError.  Bad if it's a gratuitous
MyValueError that doesn't say anything more useful about the condition.

Do rules, even "rules of thumb", help us write code that makes sense?
I don't know, but it's not easy to come up with a good rule of thumb!
Obviously the real quality of a system depends on the effort and insight
the programmer brings to bear on it.

I'm not sure it's clear that a programmer must have an inventory of
potential exceptions.  For common programming applications, I think
we trap exceptions because we think we can do something appropriate,
because we think we understand the nature of that problem.  A list
of names of exceptions isn't enough, we need to understand the exceptions
in terms of the problems they represent in that context.  I don't think
you can make a list of exceptions, for any non-trivial function, that
can possibly be both complete and meaningful.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list