关于Python中异常(Exception)的汇总

 更新时间:2017年01月18日 10:48:38   作者:jessonsh  
异常是指程序中的例外,违例情况。异常机制是指程序出现错误后,程序的处理方法。当出现错误后,程序的执行流程发生改变,程序的控制权转移到异常处理。下面这篇文章主要汇总了关于Python中异常(Exception)的相关资料,需要的朋友可以参考下。

前言

Exception类是常用的异常类,该类包括StandardError,StopIteration, GeneratorExit, Warning等异常类。python中的异常使用继承结构创建,可以在异常处理程序中捕获基类异常,也可以捕获各种子类异常,python中使用try...except语句捕获异常,异常子句定义在try子句后面。

Python中的异常处理

异常处理的语句结构

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。

说明

  • else和finally是可选的,可能会有0个或多个except,但是,如果出现一个else的话,必须有至少一个except。
  • 不管你如何指定异常,异常总是通过实例对象来识别,并且大多数时候在任意给定的时刻激活。一旦异常在程序中某处由一条except子句捕获,它就死掉了,除非由另一个raise语句或错误重新引发它。

raise语句

raise语句用来手动抛出一个异常,有下面几种调用格式:

  • raise #可以在raise语句之前创建该实例或者在raise语句中创建。
  • raise #Python会隐式地创建类的实例
  • raise name(value) #抛出异常的同时,提供额外信息value
  • raise # 把最近一次产生的异常重新抛出来
  • raise exception from E

例如:

抛出带有额外信息的ValueError: raise ValueError('we can only accept positive values')

当使用from的时候,第二个表达式指定了另一个异常类或实例,它会附加到引发异常的__cause__属性。如果引发的异常没有捕获,Python把异常也作为标准出错消息的一部分打印出来:

比如下面的代码:

try:
 1/0
except Exception as E:
 raise TypeError('bad input') from E

执行的结果如下:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeroDivisionError: division by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError('bad input') from E
TypeError: bad input

assert语句

assert主要用来做断言,通常用在单元测试中较多,到时候再做介绍。

with...as语句

with语句支持更丰富的基于对象的协议,可以为代码块定义支持进入和离开动作。

with语句对应的环境管理协议要求如下:

  • 环境管理器必须有__enter____exit__方法。

       __enter__方法会在初始化的时候运行,如果存在ass子在, __enter__函数的返回值会赋值给as子句中的变量,否则,直接丢弃。

       代码块中嵌套的代码会执行。

       如果with代码块引发异常, __exit__(type,value,traceback)方法就会被调用(带有异常细节)。这些也是由 sys.exc_info返回的相同值.如果此方法返回值为假,则异常会重新引发。否则,异常会终止。正常 情况下异常是应该被重新引发,这样的话才能传递到with语句之外。

       如果with代码块没有引发异常, __exit__方法依然会被调用,其type、value以及traceback参数都会以None传递。

下面为一个简单的自定义的上下文管理类。

class Block:
 def __enter__(self):
  print('entering to the block')
  return self
 
 def prt(self, args):
  print('this is the block we do %s' % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print('exit normally without exception')
  else:
   print('found exception: %s, and detailed info is %s' % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt('actual work!')
 raise ValueError('wrong')

如果注销到上面的raise语句,那么会正常退出。

在没有注销掉该raise语句的情况下,运行结果如下:

entering to the block
this is the block we do actual work!
found exception: <class 'ValueError'>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError('wrong')
ValueError: wrong

异常处理器

如果发生异常,那么通过调用sys.exc_info()函数,可以返回包含3个元素的元组。 第一个元素就是引发异常类,而第二个是实际引发的实例,第三个元素traceback对象,代表异常最初发生时调用的堆栈。如果一切正常,那么会返回3个None。

Python的Builtins模块中定义的Exception

|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeroDivisionError|Division (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

相关文章

  • Python的Import机制的模块与包深入理解

    Python的Import机制的模块与包深入理解

    深入理解Python的import机制有助于更好地组织代码、提高代码复用性,本文将深入研究Python的Import机制,包括模块的导入过程、命名空间与作用域、相对导入以及包的结构和导入等方面,通过丰富的示例代码,助你更全面地理解和应用这
    2024-01-01
  • 深入理解Python的元类

    深入理解Python的元类

    这篇文章主要为大家介绍了Python的元类,具有一定的参考价值,感兴趣的小伙伴们可以参考一下,希望能够给你带来帮助
    2021-11-11
  • 基于opencv实现手势控制音量(案例详解)

    基于opencv实现手势控制音量(案例详解)

    这篇文章主要介绍了基于opencv的手势控制音量和ai换脸,通过定义了一个名为 handDetector 的类,用于检测和跟踪手部,结合实例代码给大家介绍的非常详细,需要的朋友可以参考下
    2023-08-08
  • python实现生成字符串大小写字母和数字的各种组合

    python实现生成字符串大小写字母和数字的各种组合

    这篇文章主要给大家介绍了关于python生成各种字符串的方法实例,给大家提供些思路,抛砖引玉,希望大家能够喜欢
    2019-01-01
  • python之plt.hist函数的输入参数和返回值的用法解释

    python之plt.hist函数的输入参数和返回值的用法解释

    这篇文章主要介绍了python之plt.hist函数的输入参数和返回值的用法解释,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • PyQT实现菜单中的复制,全选和清空的功能的方法

    PyQT实现菜单中的复制,全选和清空的功能的方法

    今天小编就为大家分享一篇PyQT实现菜单中的复制,全选和清空的功能的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-06-06
  • Python 实现简单的shell sed替换功能(实例讲解)

    Python 实现简单的shell sed替换功能(实例讲解)

    下面小编就为大家带来一篇Python 实现简单的shell sed替换功能(实例讲解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • PyCharm+Qt Designer+PyUIC安装配置教程详解

    PyCharm+Qt Designer+PyUIC安装配置教程详解

    这篇文章主要介绍了PyCharm+Qt Designer+PyUIC安装配置教程详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-06-06
  • Python实现的多进程和多线程功能示例

    Python实现的多进程和多线程功能示例

    这篇文章主要介绍了Python实现的多进程和多线程功能,结合实例形式分析了Python多线程与多进程实现分布式系统功能相关操作技巧,需要的朋友可以参考下
    2018-05-05
  • Python爬虫获取页面所有URL链接过程详解

    Python爬虫获取页面所有URL链接过程详解

    这篇文章主要介绍了Python爬虫获取页面所有URL链接过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06

最新评论