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

后端 未结 11 2067
情歌与酒
情歌与酒 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:20

    A good and simple example for nested try/except could be the following:

    import numpy as np
    
    def divide(x, y):
        try:
            out = x/y
        except:
            try:
                out = np.inf * x / abs(x)
            except:
                out = np.nan
        finally:
            return out
    
    

    Now try various combinations and you will get the correct result:

    divide(15, 3)
    # 5.0
    
    divide(15, 0)
    # inf
    
    divide(-15, 0)
    # -inf
    
    divide(0, 0)
    # nan
    
    

    [of course we have numpy so we don't need to create this function]

提交回复
热议问题