Multiple exception syntax

P

Pierre Quentel

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
 
P

Peter Otten

Pierre said:
I find this confusing. It would be clearer for me to have :

"except Error1 or Error2 or Error3"

I see the ambiguity, but I find the above confusing, too, because it looks
like a boolean expression, which it is not. I'd rather change the syntax to
clearly separate the tuple of exception classes from the target:

"except" [expression ["to" target]] ":" suite

"to" is currently a comma. Don't expect that to happen, though.

By the way, I don't recall having seen expression containing exception
*instances*, and only learned that this is possible when I looked up the
try statement in the reference. Is this for string exceptions or has it an
application in newer code?
Or have I drunk too much lately ?

Obviously, if you have to ask :)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,266
Messages
2,571,085
Members
48,773
Latest member
Kaybee

Latest Threads

Top