Python3 错误和异常

Python 有两种错误很容易辨认:语法错误和异常。

Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。

语法错误

Python 的语法错误或者称之为解析错,是初学者经常碰到的,如下实例

>>> while True print('Hello world')
  File "<stdin>", line 1, in ?
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

这个例子中,函数 print() 被检查到有错误,是它前面缺少了一个冒号 : 。

语法分析器指出了出错的一行,并且在最先找到的错误的位置标记了一个小小的箭头。

异常

即便 Python 程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。

大多数的异常都不会被程序处理,都以错误信息的形式展现在这里:

>>> 10 * (1/0)             # 0 不能作为除数,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3             # spam 未定义,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2               # int 不能与 str 相加,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

异常以不同的类型出现,这些类型都作为信息的一部分打印出来: 例子中的类型有 ZeroDivisionError,NameError 和 TypeError。

错误信息的前面部分显示了异常发生的上下文,并以调用栈的形式显示具体信息。

 

表 1 Python常见异常类型
异常类型 含义 实例
AssertionError 当 assert 关键字后的条件为假时,程序运行会停止并抛出 AssertionError 异常 >>> demo_list = ['C语言中文网']
>>> assert len(demo_list) > 0
>>> demo_list.pop()
'C语言中文网'
>>> assert len(demo_list) > 0
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    assert len(demo_list) > 0
AssertionError
AttributeError 当试图访问的对象属性不存在时抛出的异常 >>> demo_list = ['C语言中文网']
>>> demo_list.len
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    demo_list.len
AttributeError: 'list' object has no attribute 'len'
IndexError 索引超出序列范围会引发此异常 >>> demo_list = ['C语言中文网']
>>> demo_list[3]
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    demo_list[3]
IndexError: list index out of range
KeyError 字典中查找一个不存在的关键字时引发此异常 >>> demo_dict={'C语言中文网':"c.biancheng.net"}
>>> demo_dict["C语言"]
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    demo_dict["C语言"]
KeyError: 'C语言'
NameError 尝试访问一个未声明的变量时,引发此异常 >>> C语言中文网
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    C语言中文网
NameError: name 'C语言中文网' is not defined
TypeError 不同类型数据之间的无效操作 >>> 1+'C语言中文网'
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    1+'C语言中文网'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError 除法运算中除数为 0 引发此异常 >>> a = 1/0
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    a = 1/0
ZeroDivisionError: division by zero
posted @ 2021-01-22 10:05  lunvo  阅读(564)  评论(0编辑  收藏  举报