1. 扑获异常

1.1 基本语法

把可能抛出异常(出错)的语句放在tryblock里,然后用except去扑捉(预判)可能的异常类型,如果异常类型match,就执行except模块。

try:# write some code# that might throw exception
except <ExceptionType>:# Exception handler, alert the user

比如读取一个不存在的文件会引起IOError,我们就可以提前加以处理。

try:f = open('nofile.txt', 'r')print f.read()f.close()
except IOError:print 'file not found'
file not found

执行流程是这样的:
1. First statement between try and except block are executed.
2. If no exception occurs then code under except clause will be skipped.
3. If file don’t exists then exception will be raised and the rest of the code in the try block will be skipped
4. When exceptions occurs, if the exception type matches exception name after except keyword, then the code in that except clause is executed.

1.2 扑获更多异常类型

try:<body>
except <ExceptionType1>:<handler1>
except <ExceptionTypeN>:<handlerN>
except:<handlerExcept>
else:<process_else>
finally:<process_finally>
  1. except类似于elif,当try出现异常时,挨个匹配except里的异常类型,如果匹配,执行;若果没有匹配,执行不指定异常类型的except

  2. else只有在try执行时没有异常的时候执行。

  3. finally不管try模块是否有异常抛出,都执行。

1.3 例子

num1, num2 = 1,0
try:result = num1 / num2print("Result is", result)except ZeroDivisionError:print("Division by zero is error !!")except:print("Wrong input")else:print("No exceptions")finally:print("This will execute no matter what you input")
Division by zero is error !!
This will execute no matter what you input

2. 抛出异常

raise语句抛出自己的异常。raise ExceptionClass('Your argument')

def enterage(age):if age < 0:raise ValueError("Only positive integers are allowed")if age % 2 == 0:print("age is even")try:num = int(input("Enter your age: "))enterage(num)
except ValueError:print 'Only positive integers are allowd'
except:print 'Something went wrong'
Enter your age: -3
Only positive integers are allowd

异常参考图,更多异常类型参见官方文档。

3. 操作异常

有时候我们希望能把异常对象传递给一个变量,也非常方便实现。

try:# this code is expected to throw exception
except ExceptionType as ex:# code to handle exception
try:number = int(input("Enter a number: "))print "The number entered is", numberexcept NameError as ex:print "Exception:", ex
Enter a number: one
Exception: name 'one' is not defined

Python: 异常处理相关推荐

  1. python示例异常处理与程序调试_笔记:Python异常处理与程序调试

    Python异常处理与程序调试 Python提供了强大的异常处理机制,通过捕获异常可以提高程序的健壮性.异常处理还具有释放对象,中止循环的运行等作用.在程序运行的过程中,如果发生了错误,可以返回事先约 ...

  2. Python 异常处理--raise函数用法

    Python 异常处理--raise函数用法 参考文章: (1)Python 异常处理--raise函数用法 (2)https://www.cnblogs.com/darkgui34/p/405074 ...

  3. python异常处理--try except else raise finally

    python异常处理--try except else raise finally 参考文章: (1)python异常处理--try except else raise finally (2)http ...

  4. python 异常处理 try except

    python 异常处理 try except 参考文章: (1)python 异常处理 try except (2)https://www.cnblogs.com/brave1/p/10252739. ...

  5. python异常处理(基础)

    python异常处理(基础) 参考文章: (1)python异常处理(基础) (2)https://www.cnblogs.com/fnng/p/3518202.html 备忘一下.

  6. python处理流程-Python异常处理大全(二)

    原标题:Python异常处理大全(二) 本文是Python异常处理教程的第二部分,上部分我们简单的介绍了几种异常,及其处理办法,这部分我们将更详细地对Python中产生的异常处理方法进行探讨. 函数使 ...

  7. 十一、Python异常处理

    Python异常处理 异常抛出机制,为程序开发人员提供了一种在运行时发现错误,进行回复处理,然后继续执行的能力 #!/usr/bin/python try: open('abc.txt') excep ...

  8. Python异常处理体系简介(1)

    http://developer.51cto.com/art/200902/111535.htm Python异常处理体系 1.Python内建异常体系结构 The class hierarchy f ...

  9. python异常处理_汇总三大python异常处理、自定义异常、断言原理与用法分析

    本文实例讲述了python异常处理.自定义异常.断言原理与用法.分享给大家供大家参考,具体如下: 什么是异常: 当程序遭遇某些非正常问题的时候就会抛出异常:比如int()只能处理能转化成int的对象, ...

  10. 【Python】1054 求平均值(Python异常处理练习)

    1. 题目 2. 代码 重坑,读题不仔细,导致耗时多. 题目中合法数字当只用一个的时候,输出的结果中的是number,而不是numbers # https://pintia.cn/problem-se ...

最新文章

  1. Python 读取文本时的 read/readline/readlines
  2. 圆柱属于能滚动的物体吗_一户多宅属于违建吗?怎么能拥有多一点的宅基地
  3. clickhouse大数据分析技术与实战_从销售到经营——大客户销售策略与实战技术...
  4. 华强北AirPods洛达1562A固件升级教程,带空间音频(艾创力+东莞豪锐)
  5. android 360 悬浮窗,悬浮窗的实现(如360悬浮窗效果)
  6. 屏幕录像专家V2014(附注册码)
  7. php调用纯真ip,php调用纯真IP数据库进行IP定位
  8. OAuth三方授权登录
  9. S5P4418裸机之SDIO程序
  10. 计算机组成原理一篇过
  11. AAC音频压缩(转载)
  12. C语言程序设计博客作业06
  13. 什么是跨域(CORS)?怎么解决跨域(CORS)?
  14. T-SQL查询语句(一)
  15. 用opencv-python建立纯色图
  16. java熔断器_详解spring cloud分布式关于熔断器
  17. form表单中的 action=./? 是什么意思
  18. 可以直接考全国计算机四级吗,国家计算机四级可以直接考吗
  19. 抓包工具charles的https抓包配置
  20. 图论总结tarjan算法

热门文章

  1. UML 之 C++类图关系全面剖析
  2. 中国大学MOOC北京大学唐大仕老师《Java程序设计》源码分享
  3. python中数字类型以及进制转换
  4. MT4如何设置手机app通知
  5. word文档找不到smartart_word2003SmartArt在哪里
  6. 有什么软件可以免费压缩图片?
  7. 在 Linux 下安装 HM,运行 HEVC 参考代码
  8. 棋盘放芝麻用for循环写出步骤
  9. 微信小程序开发之页面布局
  10. php twig if,twig基本语法