Python 中的嵌套 try/except

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19883531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:53:02  来源:igfitidea点击:

nested try/except in Python

pythonexception-handlingtry-catch

提问by tic

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

Which instruction have I to write in place of return to final commandsto make that any exceptreturns to the top-level instructions following the outer try? And is it an acceptable structure?

这说明有我在的地方写return to final commands作任何except跟随外尝试返回到顶级的指令?它是一个可以接受的结构吗?

Edit: Here is a toy example (I know I can do it using ifs, it's only an example; suppose you have to write it using try/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

采纳答案by Evan

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:

至少,您应该能够通过重新引发异常以避免块的其余部分来将此结构减少到仅 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

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:

真的,这不是这样做的方法,至少在这个例子中是这样。问题是您正在尝试使用诸如返回错误代码之类的异常。您应该做的是将错误消息放入异常中。此外,通常外部 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