在Python中嵌套try / except

时间:2013-11-09 21:50:50

标签: python exception-handling try-catch

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返回到外部尝试后的顶级指令?它是一个可接受的结构吗?

编辑:这是一个玩具示例(我知道我可以使用if执行此操作,这只是一个示例;假设您必须使用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

1 个答案:

答案 0 :(得分:23)

至少你应该能够通过重新添加异常来将此结构减少到只有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