python 常见异常

参考:https://www.runoob.com/python/python-exceptions.html

常见异常:

NameError: 尝试访问一个未声明的变量,比如:

>>> print(hp)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'hp' is not defined
>>> _dict = {count:1}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'count' is not defined

ZeroDivisionError: 除数为0,比如:

>>> print(1/0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

SyntaxError: 解释器语法错误,表示代码中有不正确的结构,一般在编译时发生。比如:

>>> if
  File "<stdin>", line 1
    if
     ^
SyntaxError: invalid syntax
>>> _dict = {count = 1}
  File "<stdin>", line 1
    _dict = {count = 1}
                   ^
SyntaxError: invalid syntax

IndexError: 请求索引超出序列范围,在列表中较为常见。比如:

>>> _list = []
>>> print(_list[1])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

AttributeError: 尝试访问未知的对象属性,比如:

>>> _dict = {}
>>> print(_dict.count)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'count'

KeyError: 请求一个不存在的字典关键字,比如:

>>> _dict = {'Count':1}
>>> print(_dict['count'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'count'

IOError: 尝试打开一个不存在的文件导致,比如:

>>> file = open('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: '1'

ValueError: 试图将一个与数字无关的类型转换为整数,比如:

>>> int('str')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'str'

ImportError: 导入模块失败,比如:

>>> import ss
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named ss

IndentationError: 缩进错误,比如:

>>> ss = 0
>>> if ss == 0:
...
  File "<stdin>", line 2

    ^
IndentationError: expected an indented block

 RuntimeError: 运行错误,比如:

# 递归阶乘
def Recursion_factorial(num):
    if num > 1:
        return num * Recursion_factorial(num - 1)

    return 1

if __name__ == '__main__':
    result = Recursion_factorial(1000)
    print(result)

# RuntimeError: maximum recursion depth exceeded
# 错误原因: 超过python递归深度
# 解决方式: sys.setrecursionlimit(2000) 设置递归层数再大些

 

posted @ 2019-11-12 16:03  Code~  阅读(379)  评论(0)    收藏  举报