try:
  commands
  try:
    commands
    try:
      commands
      try:
        commands
      except:
        commands
        return to final commands
    except:
      commands
      return to final commands
  except:
    commands
    return to final commands
except:
  commands

final commands

我必须写哪个指令来代替return to final commands以使任何except在外部尝试之后返回到顶级指令?它是可接受的结构吗?
编辑:这里有一个玩具例子(我知道我可以用ifs来做,这只是一个例子;假设你必须用try/except来写它)。
# calculate arcsin(log(sqrt(x)-4))
x = choose one yourself
try
  x1=sqrt(x)
  return to final message
  try
    x1=log(x1-4)
    return to final message
    try
      x2=arcsin(x1)
      return to final message
    except
      message="Impossible to calculate arcsin: maybe an argument outside [-1,+1]?"
  except
    message="Impossible to calculate logarithm: maybe a not positive argument?"
except
  message="impossible to calculate square root: maybe a negative argument?"
final message:
print message

最佳答案

至少,通过重新引发异常以避免块的其余部分,您应该能够将此结构减少到仅2个嵌套级别:

# 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

实际上,至少在本例中,这不是实现这一点的方法。问题是您试图使用异常,如返回错误代码。您应该做的是将错误消息放入异常中。此外,通常情况下,外部的try/except将处于更高级别的功能中:
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

关于python - 在Python中嵌套try/except,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19883531/

10-13 01:20