Are nested try/except blocks in python a good programming practice?

后端 未结 11 2061
情歌与酒
情歌与酒 2020-12-07 08:33

I\'m writing my own container, which needs to give access to a dictionary inside by attribute calls. The typical use of the container would be like this:

dic         


        
11条回答
  •  一整个雨季
    2020-12-07 09:24

    One thing I like to avoid is raising a new exception while handling an old one. It makes the error messages confusing to read.

    For example, in my code, I originally wrote

    try:
        return tuple.__getitem__(self, i)(key)
    except IndexError:
        raise KeyError(key)
    

    And I got this message.

    >>> During handling of above exception, another exception occurred.
    

    What I wanted was this:

    try:
        return tuple.__getitem__(self, i)(key)
    except IndexError:
        pass
    raise KeyError(key)
    

    It doesn't affect how exceptions are handled. In either block of code, a KeyError would have been caught. This is merely an issue of getting style points.

提交回复
热议问题