Multiple exception syntax

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pierre Quentel

    Multiple exception syntax

    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=ConfigPars er.ConfigParser ()
    3 conf.read("conf ig.ini")
    4
    5 try:
    6 PORT=conf.get(" Server","port")
    7 except ConfigParser.No OptionError,Con figParser.NoSec tionError:
    8 PORT=80
    9
    10 try:
    11 language=conf.g et("Translation ","language ")
    12 except ConfigParser.No OptionError,Con figParser.NoSec tionError:
    13 language="defau lt"
    ----------------------

    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\Prog rammes Python\multiple ExceptBug.py", line 11
    , in ?
    language=conf.g et("Translation ","language ")
    File "C:\Python23\li b\ConfigParser. py", line 505, in get
    raise NoSectionError( section)
    AttributeError: NoOptionError instance has no __call__ method

    My bug was in line 7, where ConfigParser.No SectionError 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


  • Peter Otten

    #2
    Re: Multiple exception syntax

    Pierre Quentel wrote:
    [color=blue]
    > I find this confusing. It would be clearer for me to have :
    >
    > "except Error1 or Error2 or Error3"[/color]

    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?
    [color=blue]
    > Or have I drunk too much lately ?[/color]

    Obviously, if you have to ask :-)

    Peter



    Comment

    Working...