【Python】标准异常及常用异常实例

      在Python开发过程中,经常会遇到各种各样的报错情况,所以了解Python中的各种报错就很有必要。小白最近整理了一下Python中经常遇到的报错情况,并列举了案例,如下表格,还有一些报错情况,待尝试~

AssertionError断言语句失败:当 assert 关键字后的条件为假时,程序运行会停止并抛出 AssertionError 异常l1 = ['111a']
assert len(l1)>0
l2 = []
assert len(l2)>0
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-4-5d421c3e78d3> in <module>
      1 l2 = []
----> 2 assert len(l2)>0
IndexError序列中没有此索引(index):索引超出序列范围会引发此异常l1 = ['111a']
l1[1]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-130763729f9e> in <module>
      1 l1 = ['111a']
----> 2 l1[1]

IndexError: list index out of range
KeyError映射中没有这个键:字典中查找一个不存在的关键字时引发此异常dict={'张三':"50"}
dict["李四"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-9-77ca0e0db50c> in <module>
      1 dict={'张三':"50"}
----> 2 dict["李四"]

KeyError: '李四'
AttributeError对象没有这个属性:当试图访问的对象属性不存在时抛出的异常l1 = ['111a']
l1.len
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-f1db6a9cf562> in <module>
      1 l1 = ['111a']
----> 2 l1.len

AttributeError: 'list' object has no attribute 'len'
NameError未声明/初始化对象 (没有属性):尝试访问一个未声明的变量时,引发此异常l1 = ['111a']
l2 = []
l3
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-75536776ce4c> in <module>
      1 l1 = ['111a']
      2 l2 = []
----> 3 l3

NameError: name 'l3' is not defined
TypeError对类型无效的操作:不同类型数据之间的无效操作1+'aaa
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-9e5eb69813e3> in <module>
----> 1 1+'aaa'

TypeError: unsupported operand type(s) for +: 'int' and 'str'
ZeroDivisionError除(或取模)零 (所有数据类型):除法运算中除数为 0 引发此异常a = 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-15-6c16767f6731> in <module>
----> 1 a = 1/0

ZeroDivisionError: division by zero
StopIteration迭代器没有更多的值iterable = iter([1,2])
print(next(iterable))
print(next(iterable))
print(next(iterable))
1
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-16-0f9614553e6f> in <module>
      2 print(next(iterable))
      3 print(next(iterable))
----> 4 print(next(iterable))

StopIteration: 
ImportError导入模块/对象失败import sy
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-29-1afd4de6e860> in <module>
----> 1 import sy

ModuleNotFoundError: No module named 'sy'
SyntaxErrorPython 语法错误for i in range(0,10)):
 File "<ipython-input-30-3edb23e8bd2e>", line 1
    for i in range(0,10)):
                        ^
SyntaxError: invalid syntax
ValueError传入无效的参数#range方法的第三个参数不可为0
for i in range(1, 3, 0):
    print (i)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-35-3663a22f4899> in <module>
----> 1 for i in range(1, 3, 0):
      2     print (i)

ValueError: range() arg 3 must not be zero
BaseException所有异常的基类 
SystemExit解释器请求退出 
KeyboardInterrupt用户中断执行(通常是输入^C) 
Exception常规错误的基类 
GeneratorExit生成器(generator)发生异常来通知退出 
StandardError所有的内建标准异常的基类 
ArithmeticError所有数值计算错误的基类 
FloatingPointError浮点计算错误 
OverflowError数值运算超出最大限制 
EOFError没有内建输入,到达EOF 标记 
EnvironmentError操作系统错误的基类 
IOError输入/输出操作失败 
OSError操作系统错误 
WindowsError系统调用失败 
LookupError无效数据查询的基类 
MemoryError内存溢出错误(对于Python 解释器不是致命的) 
UnboundLocalError访问未初始化的本地变量 
ReferenceError弱引用(Weak reference)试图访问已经垃圾回收了的对象 
RuntimeError一般的运行时错误 
NotImplementedError尚未实现的方法 
IndentationError缩进错误 
TabErrorTab 和空格混用 
SystemError一般的解释器系统错误 
UnicodeErrorUnicode 相关的错误 
UnicodeDecodeErrorUnicode 解码时的错误 
UnicodeEncodeErrorUnicode 编码时错误 
UnicodeTranslateErrorUnicode 转换时错误 
Warning警告的基类 
DeprecationWarning关于被弃用的特征的警告 
FutureWarning关于构造将来语义会有改变的警告 
OverflowWarning旧的关于自动提升为长整型(long)的警告 
PendingDeprecationWarning关于特性将会被废弃的警告 
RuntimeWarning可疑的运行时行为(runtime behavior)的警告 
SyntaxWarning可疑的语法的警告 
UserWarning用户代码生成的警告 

为了更加系统的了解报错的层级情况,下面列出Python中错误的层级结构,以下是 Python 内置异常类的层次结构:

BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
      +-- StopIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning
 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值