13
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
4

1 回答 1

34

至少,您应该能够通过重新引发异常以避免块的其余部分来将此结构减少到只有 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
于 2013-11-10T07:13:47.910 回答