查看全部 Python3 基础教程
语法错误
语法错误,也叫做解析错误。
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
解析器会显示错误行,并用“小箭头”指向错误行中最早检测到的错误点。错误的原因(或检测到的位置)位于“小箭头”的前面,上例中,错误在函数 print() 处被检测到,因为该函数前面少了一个冒号 :
。为防止代码来自某个脚本,解析器还会打印出文件名和行号以告知在何处查找错误。
异常
即使某个语句或表达式的语法正确,在执行时也可能会引起错误。执行过程中检测到的错误称为异常,且出现该错误是有条件的。大多数异常不由程序处理,而是引起错误消息,如下所示:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> 4 + spam*3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'spam' is not defined
>>> '2' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
错误消息的最后一行指明发生的情况。异常有不同的类型,且类型会作为错误消息的一部分打印出来:上例中的异常类型有 ZeroDivisionError、NameError 和 TypeError。作为异常类型打印出的字符串是所发生的内置异常的名称,所有内置异常都是这样,但用户定义的异常可能不是(尽管这是一个有用的约定)。标准异常的名称是内置的标识符,不是保留的关键字。
该行的其余部分提供了基于该异常类型及其原因的详细信息。
错误消息的前面部分以堆栈回溯的形式展示了异常发生所在的上下文。通常,它会包含列出源代码行的堆栈回溯,但是,它不会显示从标准输入读取的代码行。
内置异常及其含义可以参考 Built-in Exceptions。
处理异常
可以编程处理指定的异常。以下例子不断要求用户输入一个有效整数,但是允许用户中断程序(使用 Control-C
或者任何操作系统支持的方法)。需要注意的是用户发出的中断是通过引发 KeyboardInterrupt 异常生成的。
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
try 语句按如下方式工作:
- 首先,执行
try
子句(在try
和except
之间的部分)。 - 如果没有发生异常,则会跳过
except
子句,然后try
语句执行结束。 - 如果在
try
子句执行过程中发生了异常,则会跳过该子句的其余部分。然后如果该异常类型与except
关键字后面的异常名称匹配,则会执行对应的except
子句,然后继续执行try
语句之后的代码。 - 如果发生了一个异常,且在
except
子句中没有与其匹配的异常名称,则会将该异常传递给外部try
语句。如果最终仍找不到对应的处理语句,那么它就成了一个未处理异常,这时会终止程序运行,并显示如上所示的信息。
一个 try
语句可以有多个 except
子句,为不同的异常指定各自的处理程序,最多只执行一个处理程序。异常处理程序只处理相应 try
子句中发生的异常,不会处理同一个 try
语句中其他处理程序中发生的异常。except
子句可以将多个异常命名为一个带圆括号的元组,例如:
... except (RuntimeError, TypeError, NameError):
... pass
如果 except
子句中的类与 try
中抛出的异常是同一个类或是该异常的基类,则兼容该异常,但如果 except
子句列出的是异常的派生类,则不兼容该异常。下例将按该顺序打印 B, C, D:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
注意,如果将以上
except
子句顺序倒过来,即将except B
放在首位,则会打印 B, B, B —— 触发第一个匹配的except
子句。
最后一个 except
子句可以省略异常名称,其作用如同一个通配符。由于这种方式很容易掩盖真正的程序错误,因此使用它时要十分小心。它也可以打印出错误信息,然后将该异常重新抛出,这样调用者也能处理该异常。
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
try … except
语句有一个可选的 else
子句,该子句只能出现在所有 except
子句后面。这适用于如果 try
子句没有抛出异常就必须执行的代码。
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
使用 else
子句要好过向 try
子句添加额外代码,因为它避免了意外捕获不是由 try … except
语句所保护的代码抛出的异常。
当某个异常发生时,它可能有一个关联值,也叫做异常参数。该参数是否存在、是什么类型,取决于异常类型。
except
子句可以在异常名称后面指定一个变量,该变量与异常实例绑定,并将异常参数存储在 instance.args
中。为方便起见,异常实例定义了 __str__(),这样就能直接打印异常参数,而不需引用 .args
。也可以在抛出异常前先实例化该异常,并根据需要向其添加一些属性。
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
对于未处理的异常,如果它有参数,则参数会作为错误信息的最后一部分(“明细”)打印出来。
异常处理程序不仅可以直接处理发生在 try
子句中的异常,也能间接处理在 try
子句中调用的函数中发生的异常。例如:
>>> def this_fails():
... x = 1/0
...
>>> try:
... this_fails()
... except ZeroDivisionError as err:
... print('Handling run-time error:', err)
...
Handling run-time error: division by zero
抛出异常
raise 语句允许强制抛出指定的异常,例如:
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
raise
的唯一参数表明了要抛出的异常,该参数要么是一个异常实例(如上例),要么是一个异常类(该类派生自 Exception),如果是异常类,默认会用它的无参构造器初始化一个异常实例。
raise ValueError # shorthand for 'raise ValueError()'
如果只是要确定是否抛出了异常,但又不打算处理它,则可以用一种更简单的 raise
语句重新引发该异常。
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
异常链
raise 语句允许用一个可选的 from
开启异常链,例如:
# exc must be exception instance or None.
raise RuntimeError from exc
异常链可用于异常转换,例如:
>>> def func():
... raise IOError
...
>>> try:
... func()
... except IOError as exc:
... raise RuntimeError('Failed to open database') from exc
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<stdin>", line 2, in func
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError: Failed to open database
当异常在 except
或 finally
子句中被抛出,异常链就会自动发生,可以用 from None
禁止异常链。
>>> try:
... open('database.sqlite')
... except OSError:
... raise RuntimeError from None
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
RuntimeError
关于异常链机制的更多内容,可以参考 Built-in Exceptions。
用户定义的异常
在程序中可以通过创建新的异常类来命名自己的异常(关于 Python 类可以参考 Classes)。异常类通常应该直接或间接地从 Exception 类派生。
异常类可以像其他类一样做任何事情,但通常只是简单地提供多个属性,以供异常处理程序提取相关的错误信息。当创建一个可以抛出若干不同错误的模块时,常见的做法是为该模块定义一个异常基类,然后为不同的错误状况派生特定的异常子类。
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
与标准异常相似,大多数异常的命名都以“Error”结尾。
许多标准模块都会定义自身的异常,用来报告这些模块所定义的函数中可能发生的错误。关于类的更多信息可以参考 Classes 章节。
定义清理动作
try 语句还有一个可选的子句,用于定义在任何情况下都必须执行的清理动作。例如:
>>> try:
... raise KeyboardInterrupt
... finally:
... print('Goodbye, world!')
...
Goodbye, world!
KeyboardInterrupt
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
如果出现了 finally
子句,则它将作为在 try
语句完成前的最终任务来执行。不论 try
语句是否产生异常,finally
子句都会执行。
以下几点讨论了发生异常时更多复杂的情况:
-
如果在
try
子句执行期间发生异常,该异常可能会被某个except
子句处理。如果该异常没有被except
子句处理,则会在finally
子句执行后重新抛出该异常。 -
在
except
或else
子句执行期间可能发生异常,同样地,该异常会在finally
子句执行后被重新抛出。 -
如果
try
语句运行到一个break
,continue
或return
语句,则finally
子句会在这些语句执行前被执行。 -
如果
finally
子句中包含一个return
语句,则返回值将是finally
子句中的return
语句中的值,而不是try
子句中的return
语句中的值。
示例:
>>> def bool_return():
... try:
... return True
... finally:
... return False
...
>>> bool_return()
False
更复杂的示例:
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
上例中,finally
子句在任何情况下都会执行。两个字符串相除而抛出的 TypeError 没有被 except
子句处理,因此在 finally
子句执行完成后被重新抛出。
实际应用中,finally
子句在释放诸如文件或网络连接这样的资源时很有用,不论该资源的使用是否成功。
预定义的清理动作
一些对象定义了标准的清理动作,这些动作会在该对象不再被需要时执行,不论对该对象的使用是成功还是失败。
下例中尝试打开一个文件并打印其内容:
for line in open("myfile.txt"):
print(line, end="")
这段代码的问题是在代码执行完成后,文件仍然会在一段不确定的时间中处于打开状态。对于简单的脚本这不会引起问题,但对于大型应用这可能就是个问题。
with 语句可以让类似文件的对象在使用后确保被及时和正确地清理。
with open("myfile.txt") as f:
for line in f:
print(line, end="")
在代码执行完成后,文件
f
总会被关闭,即使在执行期间发生问题也会如此。类似文件这样提供了预定义清理动作的对象在其文档中都指明了这点。