Python中的异常处理

异常处理的语句结构

 --------------------------------------------------------------------注:如果你对python感兴趣,我这有个学习Python基地,里面有很多学习资料,感兴趣的+Q群:895817687--------------------------------------------------------------------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 zeroThe 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 selfdef 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 Falsewith 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中异常(Exception)的总结相关推荐

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

    想了解Python中异常重试的解决方案详解的相关内容吗,标点符在本文为您仔细讲解Python异常重试解决方案的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,重试,python ...

  2. Python 中异常嵌套

    Python 中异常嵌套 参考文章: (1)Python 中异常嵌套 (2)https://www.cnblogs.com/johnyang/p/10409153.html 备忘一下.

  3. python中异常好用的工具

    [TOC] python中异常好用的工具 PrettyErrors 安装 它的安装特别的简单,直接pip就可以 pip install pretty_errors #没有安装pip的,可以采用下面的方 ...

  4. python中异常的处理及断言,包括异常类型、异常捕获、主动跑出异常和断言

    一.异常类型介绍 什么是异常?异常即是一个事件,该事件会在程序执行过程中发生,会影响程序的正常执行,一般情况下,在python无法正常处理程序时就会发生一个异常.异常是python对象,表示一个错误. ...

  5. python中异常和错误是一个概念_Python的异常概念介绍以及处理

    一.什么是异常处理 定义:异常处理就是我们在写Python时,经常看到的报错信息,例如;NameError TypeError ValueError等,这些都是异常. 异常是一个事件,改事件会在程序执 ...

  6. Oracle存储过程中异常Exception的捕捉和处理

    Oracle存储过程中异常的捕捉和处理 CREATE OR REPLACE Procedure Proc_error_process ( v_IN in Varchar2, v_OUT Out Var ...

  7. php 异常 重试,Python中异常重试的解决方案详解

    前言 大家在做数据抓取的时候,经常遇到由于网络问题导致的程序保存,先前只是记录了错误内容,并对错误内容进行后期处理. 原先的流程: def crawl_page(url): pass def log_ ...

  8. python中异常的姓名

    AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常:基本上是无法打开文件 ImportError 无法引入模块或包:基本上是 ...

  9. Python语法异常 Exception

    常见异常: Exception                        所有异常的基类 AttributeError                 特性应用或赋值失败时引发 IOError  ...

最新文章

  1. Hadoop之Storm命令
  2. On-Heap与Off-Heap
  3. 【Anaconda】安装源---豆瓣,清华
  4. java多线程学习-java.util.concurrent详解
  5. 先学c语言还是先学java_是先学 java好还是先学c语言好
  6. 远程接入-天翼5系统让ERP穿越时空!
  7. 【前端工程师手册】说清楚JavaScript中的相等性判断
  8. K8S 核心组件 kubelet 与 kube-proxy 分析
  9. ajax get post
  10. keil转换c为汇编语言,如何用Keil生成bin、汇编、C与汇编混合文件?
  11. 初用mescroll-uni
  12. [ 隧道技术 ] cpolar 工具详解之将内网端口映射到公网
  13. c语言第三章课后作业答案,C语言第三章习题带答案
  14. iOS iOS 地图与定位开发系列教程
  15. 【深度首发】死磕“2D转3D”的聚力维度,能否成为影视人工智能行业的独角兽?丨Xtecher 封面
  16. 【转载】ADB命令使用大全
  17. 申请苹果个人开发者账号流程
  18. 董树义 近代微波测量技术_微波和微波信号的分析方法介绍
  19. linux 欢迎语,一日一技 | 如何让你的终端欢迎语好看又有趣
  20. linux下设置定时执行脚本

热门文章

  1. 【Java报错】Greenplum数据库报错 Value can not be converted to requested type 问题解决(踩坑分享)
  2. 【身份认证及权限控制一】单点登录
  3. JAVA——基于HttpClient的通过单点登录方式(统一身份认证平台)登录正方教务系统[1999-2020]基本解决方案
  4. Number of Components
  5. Applese 的QQ群
  6. linux修改磁盘盘符,debian下修改磁盘阵列盘符
  7. git回退到之前版本和合并分支查看当前分支切换分支
  8. git remote add Mycat https://github.com/MyCATApache/Mycat-Server.git
  9. nginx学习之location块
  10. Java21-day12【网络编程(网络编程入门(ip地址、端口、协议、InetAddress)、UDP通信程序、TCP通信程序)】