笔记-python-tutorial-8.errors and exceptions
笔记-python-tutorial-8.errors and exceptions
1. errors and exceptions
1.1. syntax errors
>>> while True print('Hello world')
File "<stdin>", line 1
while True print('Hello world')
^
SyntaxError: invalid syntax
1.2. 异常处理
>>> while True:
... try:
... x = int(input("Please enter a number: "))
... break
... except ValueError:
... print("Oops! That was no valid number. Try again...")
...
try语句工作原理:
- 首先,执行try和except之间的语句;
- 如果没有异常出现,except语句后的内容不执行,try语句执行结束;
- 如果在执行第一步时出现异常,剩余语句将跳过;如果抛出的异常类型与except后的关键字匹配,except部分语句执行;
- 如果出现异常但不匹配except给出的关键字类型,except后的语句将跳过,异常被抛给更外围的try语句,如果没有任何try语句捕获该异常,则输出缺省的出错信息。
一个try可以有多个except部分。
... except (RuntimeError, TypeError, NameError):
... pass
更好的写法,最后一个except语句最好不带异常名,这样它可以处理所有的异常信息。
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
else语句,如果没有异常则执行此语句。
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
try-finally语句,无论是否有异常,都将执行该语句。
try:
<语句>
finally:
<语句> #退出try时总会执行
raise
except语句可以在异常名后指定一个变量,这个变量与一个异常实例绑定,参数存于instance.args
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print(type(inst)) # the exception instance
... print(inst.args) # arguments stored in .args
... print(inst) # __str__ allows args to be printed directly,
... # but may be overridden in exception subclasses
... x, y = inst.args # unpack args
... print('x =', x)
... print('y =', y)
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
1.3. raising exceptions
raise语句可以触发一个异常。
raise [Exception [, args [, traceback]]]
>>> raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: HiThere
1.4. 自定义异常
通过创建新的异常类,用户可以定义自己的异常类。一般情况下从Exception类直接或间接派生类。
异常类和其它类在本质上没什么不同,但一般只用异常类提供异常信息。
1.5. 异常清理
try…finally语句可以实现异常清理功能。
>>> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
1.6. 预定义清理操作
部分对象定义了标准清理操作,当该对象不在使用时执行,不论对该对象的操作成功与否。
典型的是文件打开和关闭,在这种情况下通常使用with语句。
with open("myfile.txt") as f:
for line in f:
print(line, end="")
笔记-python-tutorial-8.errors and exceptions的更多相关文章
- 《The Python Tutorial》——Errors and Exceptions 阅读笔记
Errors and Exceptions 官方文档:https://docs.python.org/3.5/tutorial/errors.html python中所有的异常都继承自BaseExce ...
- [译]The Python Tutorial#8. Errors and Exceptions
[译]The Python Tutorial#Errors and Exceptions 到现在为止都没有过多介绍错误信息,但是已经在一些示例中使用过错误信息.Python至少有两种类型的错误:语法错 ...
- Python Tutorial 学习(八)--Errors and Exceptions
Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...
- Python Tutorial笔记
Python Tutorial笔记 Python入门指南 中文版及官方英文链接: Python入门指南 (3.5.2) http://www.pythondoc.com/pythontutorial3 ...
- 笔记-python lib-pymongo
笔记-python lib-pymongo 1. 开始 pymongo是python版的连接库,最新版为3.7.2. 文档地址:https://pypi.org/project/pymong ...
- [译]The Python Tutorial#4. More Control Flow Tools
[译]The Python Tutorial#More Control Flow Tools 除了刚才介绍的while语句之外,Python也从其他语言借鉴了其他流程控制语句,并做了相应改变. 4.1 ...
- [Notes] Learn Python2.7 From Python Tutorial
I have planed to learn Python for many times. I have started to learn Python for many times . Howeve ...
- Python Tutorial 学习(六)--Modules
6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...
- Handling Errors and Exceptions
http://delphi.about.com/od/objectpascalide/a/errorexception.htm Unfortunately, building applications ...
随机推荐
- POS开发问题 - 跳转页面更新,返回还原旧数据
问题描述:由于需求的需要,路由需要加上缓存 <keep-alive> ,还要实现跳转就初始化,返回就还原的需求.意思就是:页面 A 跳转到页面 B ,页面 B 要初始化数据,但是 页面 B ...
- A promise tomorrow is worth a lot less than trying today.
A promise tomorrow is worth a lot less than trying today.明日的承诺远不及今日的行动.
- JAVA方法定义和调用
类的方法代表的是实例的某种行为或功能 定义类的方法 访问修饰 类型 方法名(参数列表){ //方法体 } 1.把方法当作一个模块,是个“黑匣子”,完成某个特定的功能,并返回处理结果 2.方法分类“ 返 ...
- WPF学习一:XAML的资源(Resources)结构
一个初学者,把知识做个积累,如果有不对的地方,还请高手指出,谢谢! 先看一段代码:(下面是以Window WPF进行讲解,如果是Web 的话就把<Window改为<Page 而如果是 Us ...
- PagedList.Mvc只有一行时不显示分页
PagedList.Mvc默认总是显示分页,可以通过设置DisplayMode在只有一行时不显示分页 @Html.PagedListPager(Model, page => Url.Action ...
- ubuntu16.04解决屏幕适应问题
打开ubuntu登录进去后,输入: sudo apt-get installopen-vm-tools sudo apt-get install open-vm* 然后重启(reboot),即可解决 ...
- SharePoint Survey – Custom Action
<?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://sc ...
- File 与 Log #3--动态加入控件,[图片版]访客计数器(用.txt档案来记录)
File 与 Log #3--动态加入控件,[图片版]访客计数器(用.txt档案来记录) 以前的两篇文章(收录在书本「上集」的第十七章) 请看「ASP.NET专题实务」,松岗出版 File 与 Log ...
- 使用Eclipse连接SAP云平台上的HANA数据库实例
SAP云平台(Cloud Platform)上的HANA数据库实例有两种方式访问: 1. 通过SAP云平台的基于网页版的Development Tool:SAP HANA Web-Based Deve ...
- 撸了个 django 数据迁移工具 django-supertube
撸了个 django 数据迁移工具 django-supertube 支持字段映射和动态字段转化. 欢迎 star,issue https://github.com/FingerLiu/django- ...