nested try/except in Python

后端 未结 1 825
南旧
南旧 2021-02-19 20:52
try:
  commands
  try:
    commands
    try:
      commands
      try:
        commands
      except:
        commands
        return to final commands
    except:
              


        
1条回答
  •  清酒与你
    2021-02-19 21:06

    At the very least you should be able to reduce this structure to only 2 nested levels by reraising the exception to avoid the rest of the block:

    # calculate arcsin(log(sqrt(x)-4))
    x = ?
    message = None
    try:
        try:
            x1 = sqrt(x)
        except Exception:
            message = "can't take sqrt"
            raise
        try:
             x1 = log(x1-4)
        except Exception:
            message = "can't compute log"
            raise
        try:
            x2 = arcsin(x1)
        except Exception:
            message = "Can't calculate arcsin"
            raise
    except Exception:
        print message
    

    Really, this is not the way to do it, at least in this example. The problem is that you are trying to use exceptions like return error codes. What you should be doing is putting the error message into the exception. Also, normally the outer try/except would be in a higher level function:

    def func():
        try:
            y = calculate_asin_log_sqrt(x)
            # stuff that depends on y goes here
        except MyError as e:
            print e.message
        # Stuff that happens whether or not the calculation fails goes here
    
    def calculate_asin_log_sqrt(x):
        try:
            x1 = sqrt(x)
        except Exception:
            raise MyError("Can't calculate sqrt")
        try:
            x1 = log(x1-4)
        except Exception:
            raise MyError("Can't calculate log")
        try:
            x2 = arcsin(x1)
        except Exception:
            raise MyError("Can't calculate arcsin") 
        return x2
    

    0 讨论(0)
提交回复
热议问题