Python 错误类型
Python 程序中最常见的错误原因是某个语句不符合规定的用法。这种错误称为语法错误。Python 解释器会立即报告它,通常会附上原因。
Example: Error
>>> print "hello"SyntaxError: Missing parentheses in call to 'print'. Did you mean print("hello")?
在 Python 3.x 中,print 是一个内置函数,需要括号。上面的语句违反了这种用法,因此会显示语法错误。
但是很多时候,程序在运行后会导致错误,即使它没有任何语法错误。这种错误是运行时错误,称为异常。Python 库中定义了许多内置的异常。让我们看看一些常见的错误类型。
下表列出了 Python 中重要的内置异常。
索引错误
试图访问无效索引处的项目时会抛出IndexError
。
Example: IndexError
>>> L1=[1,2,3]>>> L1[3]Traceback (most recent call last):File "<pyshell#18>", line 1, in <module>L1[3]IndexError: list index out of range
ModuleNotFoundError
找不到模块时抛出ModuleNotFoundError
。
Example: ModuleNotFoundError
>>> import notamodule Traceback (most recent call last):File "<pyshell#10>", line 1, in <module>import notamodule ModuleNotFoundError: No module named 'notamodule'
键错误
找不到钥匙时抛出KeyError
。
Example: KeyError
>>> D1={'1':"aa", '2':"bb", '3':"cc"}>>> D1['4']Traceback (most recent call last):File "<pyshell#15>", line 1, in <module>D1['4']KeyError: '4'
导入错误
找不到指定函数时抛出ImportError
。
Example: ImportError
>>> from math import cube Traceback (most recent call last):File "<pyshell#16>", line 1, in <module>from math import cube ImportError: cannot import name 'cube'
停止迭代
当next()
函数超出迭代器项时,抛出StopIteration
。
Example: StopIteration
>>> it=iter([1,2,3])>>> next(it)1>>> next(it)2>>> next(it)3>>> next(it)Traceback (most recent call last):File "<pyshell#23>", line 1, in <module>next(it)StopIteration
类型错误
当对不适当类型的对象应用操作或功能时,会抛出TypeError
。
Example: TypeError
>>> '2'+2Traceback (most recent call last):File "<pyshell#23>", line 1, in <module>'2'+2TypeError: must be str, not int
值错误
当函数的参数类型不合适时,会抛出ValueError
。
Example: ValueError
>>> int('xyz')Traceback (most recent call last):File "<pyshell#14>", line 1, in <module>int('xyz')ValueError: invalid literal for int() with base 10: 'xyz'
名称错误
找不到对象时抛出NameError
。
Example: NameError
>>> age Traceback (most recent call last):File "<pyshell#6>", line 1, in <module>age NameError: name 'age' is not defined
零分割错误
当除法中的第二个运算符为零时,抛出ZeroDivisionError
。
Example: ZeroDivisionError
>>> x=100/0Traceback (most recent call last):File "<pyshell#8>", line 1, in <module>x=100/0ZeroDivisionError: division by zero
键盘中断
在程序执行过程中,当用户点击中断键(通常是 Control-C)时,会抛出KeyboardInterrupt
。
Example: KeyboardInterrupt
>>> name=input('enter your name')enter your name^c Traceback (most recent call last):File "<pyshell#9>", line 1, in <module>name=input('enter your name')KeyboardInterrupt更新于:1个月前
相关文章
- uniapp 微信小程序 控制台警告和错误处理
- EasyWeChat 生成小程序码报错 cURL错误 60
- Python环境安装,解释器配置
- 微擎后台登陆:输入密码错误次数超过5次,请在1小时后再登录
- apache常见错误:VC运行库(找不到 VCRUNTIME140.dll)
- 使用 Python 开发桌面应用程序的最佳方法是什么?
- Scala和Python有什么区别?
- 在Windows 10计算机上安装Python的最佳方法是什么?
- 使用 Python 拆分文本文件的最快方法是什么?
- Python定时任务调度框架APScheduler详解
- C#使用ToString方法数组类型格式化为字符串
- 我应该使用 PyCharm 在 Python 中编程吗?
- json python中的转储函数
- 你如何在 Python 中循环字典?
- 有哪些好的机器学习 Python 包?
- 对于初学者来说,有哪些好的 Python 示例?
- 地图函数在 Python 中有什么用?
- 如何在 Anaconda 中安装 Python 包?
- “//”在python中是什么意思?
- 对未来的技能,Go和Python哪个更好?