Multiple exception syntax
Pierre Quentel
quentel.pierre at wanadoo.fr
Fri Jan 2 03:58:01 EST 2004
Normally in Python there is no need to write parenthesis for a tuple :
a,b,c=(1,2,3)
(a,b,c)=1,2,3
are the same, and so are :
for (x,y) in enumerate(aList)
for x,y in enumerate(aList)
But with "except" the behaviour is very different with or without
parenthesis :
- "except x,y" means : if exception x is raised, then y is the instance of
the x class holding information about the exception
- "except (x,y)" means : if one of the exceptions x or y is raised (or both)
So it took me some time to figure out why this code was wrong :
----------------------
1 import ConfigParser
2 conf=ConfigParser.ConfigParser()
3 conf.read("config.ini")
4
5 try:
6 PORT=conf.get("Server","port")
7 except ConfigParser.NoOptionError,ConfigParser.NoSectionError:
8 PORT=80
9
10 try:
11 language=conf.get("Translation","language")
12 except ConfigParser.NoOptionError,ConfigParser.NoSectionError:
13 language="default"
----------------------
In my config.ini there was a [Server] section but no "port" option, and no
[Translation] section. I had this very puzzling traceback :
Traceback (most recent call last):
File "C:\Pierre\Programmes Python\multipleExceptBug.py", line 11
, in ?
language=conf.get("Translation","language")
File "C:\Python23\lib\ConfigParser.py", line 505, in get
raise NoSectionError(section)
AttributeError: NoOptionError instance has no __call__ method
My bug was in line 7, where ConfigParser.NoSectionError becomes an
instance of the NoOptionError class. With parenthesis on line 7 (and 12)
it works all right
I find this confusing. It would be clearer for me to have :
"except Error1 or Error2 or Error3"
Or have I drunk too much lately ?
Pierre
More information about the Python-list
mailing list