0

我必须处理大量的尝试/除外。我怀疑这样做的正确方法。

选项1:

inst = Some(param1, param2)
try:
    is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
    SendMail.is_valid_problem(e)

if is_valid:
    print "continue to write your code"
    ...
    *** more code with try/except ***
    ...

选项 2:

inst = Some(param1, param2)
try:
    is_valid = retry_func(partial(inst.some_other), max_retry=1)
    if is_valid:
        print "continue to write your code"
        ...
        *** more code with try/except ***
        ...
except RetryException, e:
    SendMail.is_valid_problem(e)

在选项 1 中,即使引发异常,也会测试“is_valid”,我不需要它。

在选项 2 中,我认为是正确的,但代码看起来像“回调地狱”。

我应该选择哪个选项哪个选项是正确的?

4

4 回答 4

7

让您的异常处理尽可能接近引发异常的代码。您不想在您认为不会引发相同异常的代码中意外掩盖不同的问题。

这里还有第三个选项,使用语句else:套件:try

inst = Some(param1, param2)
try:
    is_valid = retry_func(partial(inst.some_other), max_retry=1)
except RetryException, e:
    SendMail.is_valid_problem(e)
else: 
    if is_valid:
        print "continue to write your code"
        ...
        *** more code with try/except ***
        ...

只有在套件else:中没有引发异常时才会执行try套件。

于 2014-02-15T11:55:07.250 回答
2

根据您的条件,条件 1 更好,您可以使用 else 代替if is_valid

以下是一些尝试除外:

这是 try....except...else 块的简单语法:

  try:
     You do your operations here;
     ......................
  except ExceptionI:
     If there is ExceptionI, then execute this block.
  except ExceptionII:
     If there is ExceptionII, then execute this block.
     ......................
  else:
     If there is no exception then execute this block.

有多个例外的 except 子句:

  try:
     You do your operations here;
     ......................
  except(Exception1[, Exception2[,...ExceptionN]]]):
     If there is any exception from the given exception list,
     then execute this block.
     ......................
  else:
     If there is no exception then execute this block.

try-finally 子句:

  try:
     You do your operations here;
     ......................
     Due to any exception, this may be skipped.
  finally:
     This would always be executed.
于 2014-02-15T12:00:10.457 回答
1

我认为选项1更好。原因是你应该总是把 try 除了你希望抛出异常的代码。放置更多代码会增加捕获不需要的异常的风险。

于 2014-02-15T11:57:01.740 回答
0

确保如果发生错误,请将原因保留在 try 语句中。这样,它将捕获错误并在 except 部分中对其进行排序。最后也有。如果 try 不起作用,但 "except" 错误不起作用,它将执行 "finally" 语句。如果没有finally,程序就会卡住。这是一个带有 try 和 except 的示例代码: import sys import math while True: x=sys.stdin.readline() x=float(x) try: x=math.sqrt(x) y=int(x) if x !=y: print("你的数字不是平方数。") elif x==y: print("你的数字是平方数。") except(ValueError): print("你的数字是负数。"

于 2014-02-17T02:13:55.747 回答