Python 异常

在项目开发中经常碰到各种异常,比如TypeError等,这些异常都是基于Exception这个异常类的,下面列出了项目开发中经常碰见的十几种异常类型

异常名称 异常描述
BaseException 所有异常的基类
KeyboardInterrupt 用户中断执行(ctrl+c停止)
SystemExit 解释器请求退出
Exception 常规错误的基类
ValueError 传入无效参数
TypeError 变量类型错误
SystemError 解释器系统错误
TabError 空格和tab混用
IndentationError 缩进异常
SyntaxError 语法错误
RuntimeError 运行时错误
NameError 变量未定义(未声明/初始化对象)
KeyError 映射中没有这个键
IndexError 序列中没有此索引
ImportError 模块导入错误
OSError 操作系统错误
IOError 输入/输出操作错误
EOFError 没有内建输入,达到EOF标记
AttributeError 对象没有这个属性
ModuleNotFoundError 模块导入失败

KeyboardInterrupt(用户中断执行(ctrl+c停止) )

输入name后按ctrl+c停止会出现该异常

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> name
  4. KeyboardInterrupt

ValueError ( 传入无效参数 )

int()方法只可以接收字符类型的数字,当参数为hello world 时就会引发ValueError

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> a = "hello world"
  4. >>> int(a)
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. ValueError: invalid literal for int() with base 10: 'hello world'

TypeError ( 变量类型错误 )

a[0]一般是取列表/元组这种可迭代类型的,因为a是整型,不可以用索引的方式取获取,就会出现TypeError

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> a = 1
  4. >>> a[0]
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. TypeError: 'int' object is not subscriptable

TabError( 空格和tab混用)

第一个print前面用4个空格进行缩进,第二个print前面用tab缩进

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> for i in range(1,5):
  4. ... print("空格",i)
  5. ... print("tab",i)
  6. File "<stdin>", line 3
  7. print("tab",i)
  8. ^
  9. TabError: inconsistent use of tabs and spaces in indentation

IndentationError(缩进异常 )

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> for i in range(1,5):
  4. ... print("未缩进)
  5. File "<stdin>", line 2
  6. print("未缩进)
  7. ^
  8. IndentationError: expected an indented block

NameError(变量未定义(未声明/初始化对象) )

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> print(f"my name is {name}")
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. NameError: name 'name' is not defined

KeyError

a这个字典中没有B 这个键

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> a = {"A":"1"}
  4. >>> a["B"]
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. KeyError: 'B'

IndexError

a这个列表中只有2个元素,肯定找不到第三个元素

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> a = [1,2]
  4. >>> a[2]
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. IndexError: list index out of range

AttributeError

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> name = "jruing"
  4. >>> print(dir(name))
  5. ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
  6. 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
  7. >>> print(name.aaa())
  8. Traceback (most recent call last):
  9. File "<stdin>", line 1, in <module>
  10. AttributeError: 'str' object has no attribute 'aaa'

ModuleNotFoundError

  1. Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
  2. Type "help", "copyright", "credits" or "license" for more information.
  3. >>> import aaa
  4. Traceback (most recent call last):
  5. File "<stdin>", line 1, in <module>
  6. ModuleNotFoundError: No module named 'aaa'

自定义异常类

  1. class DIYError(Exception):
  2. def __init__(self,value):
  3. self.value = value
  4. def __str__(self) -> str:
  5. return str(self.value)