初学者python中常见的错误

一、常见的错误类型

1.SyntaxError:Python 解释器语法错误

>>> if

SyntaxError: invalid syntax

SyntaxError 异常是唯一不是在运行时发生的异常. 它代表 Python 代码中有一个不正确的结构, 在它改正之前程序无法执行. 这些错误一般都是在编译时发生, Python 解释器无法把你的脚本转化为 Python 字节代码. 

2.NameError:尝试访问一个未声明的变量

>>> py

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    py
NameError: name 'py' is not defined

NameError?表示我们访问了一个没有初始化的变量.

3.ZeroDivisionError:除数为零

>>> 1/0 Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero


4.IndexError:请求的索引超出序列范围

>>> list=['python']

>>> list[1]
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    list[1]
IndexError: list index out of range

5.KeyError:请求一个不存在的字典关键字

>>> dict = {'py':'pythong'}

>>> print(dict['PY'])
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(dict['PY'])
KeyError: 'PY'

映射对象, 例如字典, 是依靠关键字(keys)访问数据值的. 如果使用错误的或是不存在的键请求字典就会引发一个 KeyError异常.

6.IOError:输入/输出错误

>>> f = open('py')

Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    f = open('py')
FileNotFoundError: [Errno 2] No such file or directory: 'py'

类似尝试打开一个不存在的磁盘文件一类的操作会引发一个操作系统输入/输出(I/O)错误. 任何类型的 I/O 错误都会引发 IOError 异常.

7.AttributeError:尝试访问未知的对象属性

>>> class myClass(object):

pass

>>> myInst = myClass()
>>> myInst.py = 'python'
>>> myInst.py
'python'
>>> myInst.PY
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    myInst.PY
AttributeError: 'myClass' object has no attribute 'PY'

myInst.py 储存了一个值, 也就是实例 myInst 的 py 属性. 属性被定义后, 可以使用熟悉的点/属性操作符访问它, 但如果是没有定义属性, 例如访问 PY 属性, 将导致一个 AttributeError 异常.

二、检测和处理异常
异常可以通过 try 语句来检测。任何在 try 语句块里的代码都会被监测,检查有无异常发生。

try 语句有两种主要形式: try-except 和 try-finally . 这两个语句是互斥的, 也就是说你只 能 使 用 其 中 的 一 种 . 一 个 try 语 句 可 以 对 应 一 个 或 多 个 except 子 句 , 但 只 能 对 应 一 个 finally 子句, 或是一个 try-except-finally 复合语句.

你可以使用 try-except 语句检测和处理异常. 你也可以添加一个可选的 else 子句处理没有探测到异常的时执行的代码. 而 try-finally 只允许检测异常并做一些必要的清除工作(无论发生错误与否), 没有任何异常处理设施. 正如你想像的, 复合语句两者都可以做到.

猜你喜欢

转载自blog.csdn.net/qq_42393859/article/details/82767562