[Tutor] class and methods/functions

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Oct 6 20:42:40 CEST 2005


Hi Eric,

Quick comment on the last part of your program:

> try:
>     getProjectNames()
> except:
>     print "Got an Error"

Don't do that.  *grin*


This is considered a misuse of exceptions.  As a concrete example, say
that we have a buggy program like this:


######
>>> def showDivisions(n):
...     for x in range(n):
...         print n / x
...
######

If we run this on a few arguments, we can see good error messages:

######
>>> showDivisions(0)
>>> showDivisions(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 3, in showDivisions
ZeroDivisionError: integer division or modulo by zero
######

So here, the error message is very clear that we're doing something silly
with a division.  The error message itself looks a little scary at first,
but it's chock full of information.


But contrast this with what happens if we use an exception handler:

######
>>> try:
...     showDivisions(1)
... except:
...     print "error"
...
error
######

The word 'error' might be less intimidating than a full stack trace, but
it's also useless in terms of helping us figure out the real reason why
showDivisions is broken.


The lesson from this is: don't use exception handlers to hide errors like
that, at least, not without a strong overriding reason.


Once you've dropped the exception handler, try rerunning your program
again: you should get much better error messages, and we can start from
there.


One other comment: module import is usually done at toplevel.  You're
importing modules within classes:

######
class TPROJ:
    import re
    ...
######

and although this works, idiomatically, it's unusual enough that you may
want to avoid doing that.  Your code uses the 're' module a lot anyway, so
it makes sense to let 're' live at the toplevel, like this:

######
import re

class TPROJ:
    ...
######


Best of wishes to you!



More information about the Tutor mailing list