• SyntaxError: Python can’t parse program
  • NameError: local or global name not found
  • AttributeError: attribute reference fails
  • TypeError: operand doesn’t have correct type
  • ValueError: operand type okay, but value is illegal
  • IOError: IO system reports malfunction (e.g. file not found)

Python 异常处理


Handlers for exceptions

try & except

exception rises by any statement in body of try are handled by except statement, and execution continues after the body of the except statement

try:a = int(input("Tell me one number:"))b = int(input("Tell me another number:"))print(a/b)print("Okay")
except:print("Bug in user input.")
print("Outside")

have separate except clauses to deal with a particular type of exception

try:a = int(input("Tell me one number:"))b = int(input("Tell me another number:"))print(a/b)print("Okay")
except ValueError:print("Could not convert to a number.")
except ZeroDivisionErrorprint("balbala...")
print("Outsdie.")

else || finally

  • else:

    • body of this excuted when execution of associated try body completes with no exceptions
  • finally:
    • body of this is always excuted after try, else and except, even if they raised another error or excuted a break, continue or return.

Exception example

data = []file_name = input("Provide a name of a file of data ")try:fh = open(file_name, 'r')
except IOError:print('cannot open', file_name)
else:for new in fh:if new != '\n':addIt = new[:-1].split(',') #remove trailing \ndata.append(addIt)
finally:fh.close() # close file even if failgradesData = []
if data:for student in data:try:name = student[0:-1]grades = int(student[-1])gradesData.append([name, [grades]])except ValueError:gradesData.append([student[:], []])

Exceptions as control flow

  • raise an exception when unable to produce a result consistent with function’s specification.
  • handle error instead of simply stop the excution
def get_ratios(L1, L2):""" Assumes: L1 and L2 are lists of equal length of numbersReturns: a list containing L1[i]/L2[i] """ratios = []for index in range(len(L1)):try:ratios.append(L1[index]/float(L2[index]))except ZeroDivisionError:ratios.append(float('NaN')) #NaN = Not a Numberexcept:raise ValueError('get_ratios called with bad arg')# print something when expected error occursreturn ratios

Exercise

def fancy_divide(numbers, index):try:denom = numbers[index]for i in range(len(numbers)):numbers[i] /= denomexcept IndexError:fancy_divide(numbers, len(numbers) - 1)except ZeroDivisionError:print("-2")else:print("1")finally:print("0")

What does fancy_divide([0, 2, 4], 4)print out?

1,0,0

THIS LAST 0 COMES FROM HERE

【跟着MIT学Python】Unit 4.8 Exceptions and Assertions相关推荐

  1. python做外贸_跟着销售学python(3)---开发微信公平台(1)

    跟着销售学python(3)--- 开发微信公共平台(1) 首先交代一下, 目前我的学习背景啊: 我自己是一个创业的外贸服务公司, 自己主要做销售,学python主要目的是为了工作上的帮助吧. 自己的 ...

  2. 跟着 Alex 学python 1.安装

    声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/ 参考文档: http://www.runoob.com/python/python-tutorial.ht ...

  3. python项目策划书_跟着销售学python系列(1)--实践项目骨架(1)

    暂时不对自己的背景做任何的交代,  为什么写这个系列, 参加YC培训课最大的总结, 就是别写别思考了. 以前的写的,慢慢搬家过来吧. 学习计划: ✅  learn  python the hard w ...

  4. python学习—第一步—跟着黑马学Python(一)

    目录 学习参考 操作系统 操作系统简介 虚拟机 操作系统发展简史 Linux内核及发行版 Linux的文件和目录结构 Ubuntu的图形界面 我的Ubuntu安装 学习参考 B站黑马程序员Python ...

  5. 跟着ALEX 学python day3集合 文件操作 函数和函数式编程

    声明 : 文档内容学习于 http://www.cnblogs.com/xiaozhiqi/  一. 集合 集合是一个无序的,不重复的数据组合,主要作用如下 1.去重 把一个列表变成集合 ,就自动去重 ...

  6. 跟着官网学Python(8):输入输出

    "Python输入.输出.文件读写以及异常知识." 01 面临问题 继续跟着官网学Python,第7章输入输出. 前面已经基本学完Python的语法部分,也学会如何使用轮子,但是编 ...

  7. 跟着王进老师学Python:通过案例学条件选择-王进-专题视频课程

    跟着王进老师学Python:通过案例学条件选择-55人已学习 课程介绍         未来2年,拥有这种技能的人抢手 2017年是人工智能(AI)的元年,AI已经成为当前火热的前沿技术:而Pytho ...

  8. 跟着王进老师学Python:初识Python-王进-专题视频课程

    跟着王进老师学Python:初识Python-165人已学习 课程介绍         2017年是人工智能(AI)的元年,AI已经成为当前火热的前沿技术:而Python也在去年正式被纳入高考,要加强 ...

  9. 用python turtle画龙猫_【跟着弹簧学画画】教你一步步画出一只超萌的龙猫来!...

    原标题:[跟着弹簧学画画]教你一步步画出一只超萌的龙猫来! 龙猫,日文音译过来是豆豆龙,今天咱们就来画一个吧! 照旧先来感受下动态图↓ 1.先画耳朵,然后画出头部和身体,因为龙猫是圆滚滚的一只 画出胳 ...

最新文章

  1. idea内Maven的全局配置
  2. networkx的基本使用
  3. linux学习笔记十(Raid基本知识)
  4. JAVA: List用法
  5. php引用是什么,php引用是什么
  6. WinForm下的键盘事件(KeyPress、KeyDown)及如何处理不响应键盘事件
  7. oracle 包 解密,oracle9.1的加密解密包的用法
  8. JavaScript实现接口的三种经典方式
  9. 虚拟化系列-VMware vSphere 5.1 虚拟机管理
  10. 【python】使用枚举类
  11. 快速的mysql导入导出数据(load data和outfile)
  12. Windows 8.1 with Update MSDN 简体/英文/繁体
  13. 25G差分信号对内等长相差太大怎么处理?在哪里绕好一点
  14. android webview浏览pdf,android webview pdf查看
  15. 保持简单:纪念丹尼斯·里奇
  16. PDF转换器 将各种文件格式与PDF来回转换
  17. 我的世界rpg服务器无限点卷无限金币地址,我的世界RPG插件无限刷任何物品 | 手游网游页游攻略大全...
  18. 请求报错Required String parameter 'id' is not present
  19. 手把手教你写一个基于python+pyqt5的股票盯盘软件
  20. 要知道的命令:htop 助你心中有数 | Linux 系统下 htop 命令详解

热门文章

  1. 简明教程:只需三步成功“硬刷”BIOS为SLIC 2.1完美激活Windows 7 / Vista / XP三大系统
  2. ArcGis 中打开 shp 文件时 未知的空间参考 警告
  3. 2022-2027年中国品牌连锁酒店行业发展前景及投资战略咨询报告
  4. NC瑞士军刀 网络工具
  5. 工具 串口抓包工具 AccessPort
  6. 跨界融合引尴尬,智能珠宝能向前走远?
  7. Makefile是什么东东?有什么用?怎么用?
  8. jdk安装jre报错
  9. WORD另存为PDF时出现乱码的解决方案
  10. 2.基于文心大模型套件ERNIEKit实现文本匹配算法,模块化方便应用落地