Python 异常情况的处理方法

136 阅读2分钟

有一种处理错误的方法是很重要的。

Python为我们提供了异常处理。

如果你把几行代码包成一个try: 块。

try:
    # some lines of code

如果发生了错误,Python会提醒你,你可以使用except 块来确定发生的是哪种错误。

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>

为了捕捉所有的异常,你可以使用except ,不需要任何错误类型。

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except:
    # catch all other exceptions

如果没有发现异常,则运行else 块。

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully

一个finally 块可以让你在任何情况下执行一些操作,不管是否发生错误。

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully
finally:
    # do something in any case

会发生的具体错误取决于你正在执行的操作。

例如,如果你正在读取一个文件,你可能会得到一个EOFError 。如果你用一个数字除以0,你会得到一个ZeroDivisionError 。如果你有一个类型转换问题,你可能会得到一个TypeError

试试这段代码。

result = 2 / 0
print(result)

程序将以一个错误终止

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = 2 / 0
ZeroDivisionError: division by zero

而错误后的几行代码将不会被执行。

try: 块中添加该操作,可以让我们优雅地恢复并继续进行程序。

try:
    result = 2 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
finally:
    result = 1

print(result) # 1

你也可以在自己的代码中引发异常,使用raise 语句。

raise Exception('An error occurred!')

这引发了一个一般的异常,你可以使用拦截它。

try:
    raise Exception('An error occurred!')
except Exception as error:
    print(error)

你也可以定义你自己的异常类,扩展自Exception。

class DogNotFoundException(Exception):
    pass

pass 这里的意思是 "无",当我们定义一个没有方法的类,或者一个没有代码的函数时,也必须使用它。

try:
    raise DogNotFoundException()
except DogNotFoundException:
    print('Dog not found!')