关于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|

总结

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

(0)

相关推荐

  • Python常见异常分类与处理方法

    Python常见异常类型大概分为以下类: 1.AssertionError:当assert断言条件为假的时候抛出的异常 2.AttributeError:当访问的对象属性不存在的时候抛出的异常 3.IndexError:超出对象索引的范围时抛出的异常 4.KeyError:在字典中查找一个不存在的key抛出的异常 5.NameError:访问一个不存在的变量时抛出的异常 6.OSError:操作系统产生的异常 7.SyntaxError:语法错误时会抛出此异常 8.TypeError:类型错误,

  • Python 异常处理的实例详解

    Python 异常处理的实例详解 与许多面向对象语言一样,Python 具有异常处理,通过使用 try...except 块来实现. Note: Python v s. Java 的异常处理 Python 使用 try...except 来处理异常,使用 raise 来引发异常.Java 和 C++ 使用 try...catch 来处理异常,使用 throw 来引发异常. 异常在 Python 中无处不在:实际上在标准 Python 库中的每个模块都使用了它们,并且 Python 自已会在许多不

  • python中异常捕获方法详解

    在Python中处理异常使用的是try-except代码块,try-except代码块放入让python执行的操作,同时告诉python程序如果发生了异常该怎么办,try-except这个功能其实很多入门书籍中都放到了高级篇幅里,在入门的时候一般不会讲这个使用,尤其是作为运维人员,如果你经常写shell,转到python后估计也很少使用这个功能,这功能我觉得说明了shell和python的一个重要区别,因为python是一门真正的编程语言,像其它的编程语言php,java等都会提供异常捕获功能,

  • python自定义异常实例详解

    python自定义异常实例详解 本文通过两种方法对Python 自定义异常进行讲解,第一种:创建一个新的exception类来拥有自己的异常,第二种:raise 唯一的一个参数指定了要被抛出的异常 1.可以通过创建一个新的exception类来拥有自己的异常.异常应该继承自 Exception 类,或者直接继承,或者间接继承. >>>raiseNameError('HiThere') Traceback(most recent call last): File"<pysh

  • python中异常报错处理方法汇总

    首先异常是什么,异常白话解释就是不正常,程序里面一般是指程序员输入的格式不规范,或者需求的参数类型不对应,不全等等. Python中异常是指程序中的例外,违例情况.异常机制是指程序出现错误后,程序的处理方法.当出现错误后,程序的执行流程发生改变,程序的控制权转移到异常处理. 打个比方很多公司年终送苹果笔记本,你程序话思维以为是(MAC)电脑笔记本,结果给你个苹果+笔记本...首先类型不对,数量也不对. 先来看几个常见的报错如下: NameError 命名错误 原因是: name 'a' is n

  • 浅谈python抛出异常、自定义异常, 传递异常

    一. 抛出异常 Python用异常对象(exception object)表示异常情况,遇到错误后,会引发异常.如果异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行. raise 语句 Python中的raise 关键字用于引发一个异常,基本上和C#和Java中的throw关键字相同,如下所示: import traceback def throw_error(): raise Exception("抛出一个异常")#异常被抛出,print函数

  • Python中异常重试的解决方案详解

    前言 大家在做数据抓取的时候,经常遇到由于网络问题导致的程序保存,先前只是记录了错误内容,并对错误内容进行后期处理. 原先的流程: def crawl_page(url): pass def log_error(url): pass url = "" try: crawl_page(url) except: log_error(url) 改进后的流程: attempts = 0 success = False while attempts < 3 and not success:

  • Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)

    我们可以利用urllib来抓取远程的数据进行保存哦,以下是python3 抓取网页资源的多种方法,有需要的可以参考借鉴. 1.最简单 import urllib.request response = urllib.request.urlopen('http://python.org/') html = response.read() 2.使用 Request import urllib.request req = urllib.request.Request('http://python.org

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

    前言 Exception类是常用的异常类,该类包括StandardError,StopIteration, GeneratorExit, Warning等异常类.python中的异常使用继承结构创建,可以在异常处理程序中捕获基类异常,也可以捕获各种子类异常,python中使用try...except语句捕获异常,异常子句定义在try子句后面. Python中的异常处理 异常处理的语句结构 try: <statements> #运行try语句块,并试图捕获异常 except <name1&

  • python中的Elasticsearch操作汇总

    这篇文章主要介绍了python中的Elasticsearch操作汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 导入包 from elasticsearch import Elasticsearch 本地连接 es = Elasticsearch(['127.0.0.1:9200']) 创建索引 es.indices.create(index="python_es01",ignore=400) ingore=400 ingore是

  • python中异常的传播详解

    目录 1.异常的传播 2.如何处理异常 1.异常的传播 当在函数中出现异常时,如果在函数中对异常进行了处理,则异常不会再继续传播.如果函数中没有对异常进行处理,则异常会继续向函数调用者传播.如果函数调用者处理了异常,则不再传播,如果还没有处理,则继续向他的调用者传播,直到传递到全局作用域(主模块)如果依然没有处理,则程序终止,并且显示异常信息到控制台.所以异常的传播我们也称之为抛出异常. 异常传播示例如下: def fn1(): print('Hello fn') print(10/0) def

  • Python中列表(list)操作方法汇总

    本文实例汇总了Python中关于列表的常用操作方法,供大家参考借鉴.具体方法如下: 一.Python创建列表: sample_list = ['a',1,('a','b')] 二.Python 列表操作: 假设有如下列表: sample_list = ['a','b',0,1,3] 1.得到列表中的某一个值: value_start = sample_list[0] end_value = sample_list[-1] 2.删除列表的第一个值: del sample_list[0] 3.在列表

  • Python中psutil模块使用汇总

    简介:psutil(进程和系统实用程序)是一个跨平台库,用于检索Python中运行进程和系统利用率(CPU.内存.磁盘.网络.传感器)的信息.它主要用于系统监视.分析和限制进程资源以及管理正在运行的进程.它实现了经典UNIX命令行工具提供的许多功能,如ps.top.iotop.lsof.netstat.ifconfig.free等. 支持的平台:Linux.Windows.macOS.FreeBSD, OpenBSD, NetBSD.Sun Solaris.AIX等平台. 安装: pip ins

  • python中常用的内置模块汇总

    内置模块(一) Python内置的模块有很多,我们也已经接触了不少相关模块,接下来咱们就来做一些汇总和介绍. 内置模块有很多 & 模块中的功能也非常多,我们是没有办法注意全局给大家讲解,在此我会整理出项目开发最常用的来进行讲解. os import os # 1. 获取当前脚本绝对路径 """ abs_path = os.path.abspath(__file__) print(abs_path) # 2. 获取当前文件的上级目录 base_path = os.pat

  • Python中http请求方法库汇总

    最近在使用python做接口测试,发现python中http请求方法有许多种,今天抽点时间把相关内容整理,分享给大家,具体内容如下所示: 一.python自带库----urllib2 python自带库urllib2使用的比较多,简单使用如下: import urllib2 response = urllib2.urlopen('http://localhost:8080/jenkins/api/json?pretty=true') print response.read() 简单的get请求

  • Python中的列表知识点汇总

    Python list 在介绍 Python tuple 时,我使用了类比的方法,将其比做一个袋子,您可以在袋子中存放不同的东西.Python list 与此非常类似,因此,它的功能与袋子的功能也非常类似.但有一点是不同的,即您可以使用方括号创建 list,如清单 1 所示. 清单 1. 在 Python 中创建一个 list >>> l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8,

随机推荐