尝试语句 (Python)

Try statements (Python)

我最近发现了 try 声明(我很新),我知道 except,但我有一些问题:

1) 如何使用finally

2) 能否有多个 except 出现不同的错误?

你能举几个例子吗?

对您提出的所有问题,答案都是肯定的。

try:
    raise ArithmeticError
except ValueError:
    print("caught valueerror")
except RuntimeError:
    print("caught runtimeerror")
finally:
    print("I'll do this everytime")

输出:

I'll do this everytime

Traceback (most recent call last):
  File "<pyshell#13>", line 2, in <module>
    raise ArithmeticError
ArithmeticError

简而言之。要获得完整的解释,您最好查看教程,网上有数以百万计的教程。执行此操作时我喜欢坚持的一些一般规则是:

  • 用 try 块包围最短的代码片段。这有助于准确地隔离错误的来源。
  • 让您的例外情况尽可能具体。除非我在下面显示,否则尽量不要抓住通用的。它有时很有用,但很少见,因此您可能应该尽量不要这样做。
  • finally 总是被执行。最后 always 发生,如果发生错误,如果没有,如果你抓住了它,或者如果你没有,finally 总是会执行。使用它为您的代码创建一个干净的出口。在此处关闭所有打开的文件,保存您可能拥有的所有数据结构并解决所有未解决的问题。

我们已经看到当您遇到除上述之外没有的错误时 finally 的行为,这里是一个示例,当您提出一个您有一个例外的错误时:

try:
    raise ValueError
except ValueError:
    print("caught valueerror")
except RuntimeError:
    print("caught runtimeerror")
finally:
    print("I'll do this everytime")

caught valueerror
I'll do this everytime

即使你没有遇到错误,最终也会发生:

try:
    pass
except ValueError:
    print("caught valueerror")
finally:
    print("I'll do this everytime")

I'll do this everytime

有几种方法可以捕获任何错误(尽量避免这种情况,始终):

try:
    raise ArithmeticError
except BaseException as e:
    print("caught unknown error: ", e)
finally:
    print("I'll do this everytime")

('caught unknown error: ', ArithmeticError())
I'll do this everytime

或者你可以

import sys
try:
    raise ArithmeticError
except:
    print("caught unknown error: ", sys.exc_info()[0])
finally:
    print("I'll do this everytime")

('caught unknown error: ', <type 'exceptions.ArithmeticError'>)
I'll do this everytime

此外,try except 块可以有 else 语句。

想象一下,在这种情况下,您希望 运行 从 raise 语句中添加一些额外的代码。想象一下,该代码也可能引发错误。将该代码放在同一个 try 块中会破坏我的第一点,这不是我们应该做的事情!要用我目前展示的内容来解决这个问题,看起来应该是这样的:

executed = True
try:
    [do something]
except ValueError:
    executed = False
    print("caught valueerror")
finally:
    print("I'll do this everytime")
    if executed:
        [do something more]

我相信您会同意它比 python 通常所追求的更丑陋且可读性差。这就是为什么在 try except 块中可以添加 else 语句的原因。

else 语句 必须 遵循所有例外情况,并且只有在没有出现错误时才会执行。说真的技术,它只会执行"if it flows off the try statement"。这意味着不能有 returns、breaks、continues 等导致 "jump" 的语句。 else 还可以使您的代码更整洁、更强大,但是我很少使用它或看到它被使用:

try:
    [do something]
    pass
except ValueError:
    print("caught valueerror")
except RuntimeError:
    print("caught runtimeerror")
else:
    [do something more but only if there were no exceptions so far]
    print("I found no errors and executed else statement")
    raise ArithmeticError
finally:
    print("I'll do this everytime")

I found no errors and executed else statement
I'll do this everytime

Traceback (most recent call last):
  File "<pyshell#41>", line 7, in <module>
    raise ArithmeticError
ArithmeticError