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停止会出现该异常
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> nameKeyboardInterrupt
ValueError ( 传入无效参数 )
int()方法只可以接收字符类型的数字,当参数为hello world 时就会引发ValueError
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> a = "hello world">>> int(a)Traceback (most recent call last):File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'hello world'
TypeError ( 变量类型错误 )
a[0]一般是取列表/元组这种可迭代类型的,因为a是整型,不可以用索引的方式取获取,就会出现TypeError
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> a = 1>>> a[0]Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'int' object is not subscriptable
TabError( 空格和tab混用)
第一个print前面用4个空格进行缩进,第二个print前面用tab缩进
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> for i in range(1,5):... print("空格",i)... print("tab",i)File "<stdin>", line 3print("tab",i)^TabError: inconsistent use of tabs and spaces in indentation
IndentationError(缩进异常 )
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> for i in range(1,5):... print("未缩进)File "<stdin>", line 2print("未缩进)^IndentationError: expected an indented block
NameError(变量未定义(未声明/初始化对象) )
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> print(f"my name is {name}")Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'name' is not defined
KeyError
a这个字典中没有B 这个键
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> a = {"A":"1"}>>> a["B"]Traceback (most recent call last):File "<stdin>", line 1, in <module>KeyError: 'B'
IndexError
a这个列表中只有2个元素,肯定找不到第三个元素
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> a = [1,2]>>> a[2]Traceback (most recent call last):File "<stdin>", line 1, in <module>IndexError: list index out of range
AttributeError
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> name = "jruing">>> print(dir(name))['__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','split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>> print(name.aaa())Traceback (most recent call last):File "<stdin>", line 1, in <module>AttributeError: 'str' object has no attribute 'aaa'
ModuleNotFoundError
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32Type "help", "copyright", "credits" or "license" for more information.>>> import aaaTraceback (most recent call last):File "<stdin>", line 1, in <module>ModuleNotFoundError: No module named 'aaa'
自定义异常类
class DIYError(Exception):def __init__(self,value):self.value = valuedef __str__(self) -> str:return str(self.value)
