python 3 异常——迹忆客-ag捕鱼王app官网
python提供了两个非常重要的功能来处理python程序在运行中出现的异常和错误。你可以使用该功能来调试python程序。
- 异常处理: 本站python教程会具体介绍。
- 断言(assertions):本站python教程会具体介绍。
python标准异常
异常名称 | 描述 |
---|---|
baseexception | 所有异常的基类 |
systemexit | 解释器请求退出 |
keyboardinterrupt | 用户中断执行(通常是输入^c) |
exception | 常规错误的基类 |
stopiteration | 迭代器没有更多的值 |
generatorexit | 生成器(generator)发生异常来通知退出 |
standarderror | 所有的内建标准异常的基类 |
arithmeticerror | 所有数值计算错误的基类 |
floatingpointerror | 浮点计算错误 |
overflowerror | 数值运算超出最大限制 |
zerodivisionerror | 除(或取模)零 (所有数据类型) |
assertionerror | 断言语句失败 |
attributeerror | 对象没有这个属性 |
eoferror | 没有内建输入,到达eof 标记 |
environmenterror | 操作系统错误的基类 |
ioerror | 输入/输出操作失败 |
oserror | 操作系统错误 |
windowserror | 系统调用失败 |
importerror | 导入模块/对象失败 |
lookuperror | 无效数据查询的基类 |
indexerror | 序列中没有此索引(index) |
keyerror | 映射中没有这个键 |
memoryerror | 内存溢出错误(对于python 解释器不是致命的) |
nameerror | 未声明/初始化对象 (没有属性) |
unboundlocalerror | 访问未初始化的本地变量 |
referenceerror | 弱引用(weak reference)试图访问已经垃圾回收了的对象 |
runtimeerror | 一般的运行时错误 |
notimplementederror | 尚未实现的方法 |
syntaxerror | python 语法错误 |
indentationerror | 缩进错误 |
taberror | tab 和空格混用 |
systemerror | 一般的解释器系统错误 |
typeerror | 对类型无效的操作 |
valueerror | 传入无效的参数 |
unicodeerror | unicode 相关的错误 |
unicodedecodeerror | unicode 解码时的错误 |
unicodeencodeerror | unicode 编码时错误 |
unicodetranslateerror | unicode 转换时错误 |
warning | 警告的基类 |
deprecationwarning | 关于被弃用的特征的警告 |
futurewarning | 关于构造将来语义会有改变的警告 |
overflowwarning | 旧的关于自动提升为长整型(long)的警告 |
pendingdeprecationwarning | 关于特性将会被废弃的警告 |
runtimewarning | 可疑的运行时行为(runtime behavior)的警告 |
syntaxwarning | 可疑的语法的警告 |
userwarning | 用户代码生成的警告 |
python 中的断言
断言是一种健全性检查,可以在完成程序测试后打开或关闭它。
考虑断言的最简单方法是将其比作raise-if语句(或者更准确地说,是 raise-if-not 语句)。测试表达式,如果结果为 false,则会引发异常。
断言由 assert 语句执行,这是 python 1.5 版本中引入的最新关键字。
程序员经常在函数的开头放置断言以检查有效输入,并在函数调用之后检查有效输出。
assert 语句
当遇到断言语句时,python 会评估伴随的表达式,希望这是真的。如果表达式为 false,python 会引发assertionerror异常。
断言的语法是
assert expression[, arguments]
如果断言失败,python 使用 argumentexpression 作为 assertionerror 的参数。assertionerror 异常可以像任何其他异常一样被捕获和处理,使用 try-except 语句。如果不处理它们,它们将终止程序并产生回溯。
这是一个将给定温度从开氏度转换为华氏度的函数。由于 0° k 和它一样冷,如果它看到负温度,该函数就会退出 -
#!/usr/bin/python3
def kelvintofahrenheit(temperature):
assert (temperature >= 0),"colder than absolute zero!"
return ((temperature-273)*1.8) 32
print (kelvintofahrenheit(273))
print (int(kelvintofahrenheit(505.78)))
print (kelvintofahrenheit(-5))
执行上述代码时,会产生以下结果
32.0
451
traceback (most recent call last):
file "test.py", line 9, in
print kelvintofahrenheit(-5)
file "test.py", line 4, in kelvintofahrenheit
assert (temperature >= 0),"colder than absolute zero!"
assertionerror: colder than absolute zero!
什么是异常?
异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。
一般情况下,在python无法正常处理程序时就会发生一个异常。
异常是python对象,表示一个错误。
当python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。
异常处理
捕捉异常可以使用try/except
语句。
try/except
语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。
如果你不想在异常发生时结束你的程序,只需在try里捕获它。
语法:
以下为简单的try....except...else的语法:
try:
<语句> #运行别的代码
except <名字>:
<语句> #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句> #如果引发了'name'异常,获得附加的数据
else:
<语句> #如果没有异常发生
try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行,接下来会发生什么依赖于执行时是否出现异常。
- 如果当try后的语句执行时发生异常,python就跳回到try并执行第一个匹配该异常的except子句,异常处理完毕,控制流就通过整个try语句(除非在处理异常时又引发新的异常)。
- 如果在try后的语句里发生了异常,却没有匹配的except子句,异常将被递交到上层的try,或者到程序的最上层(这样将结束程序,并打印默认的出错信息)。
- 如果在try子句执行时没有发生异常,python将执行else语句后的语句(如果有else的话),然后控制流通过整个try语句。
实例
下面是简单的例子,它打开一个文件,在该文件中的内容写入内容,且并未发生异常:
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("this is my test file for exception handling!!")
except ioerror:
print ("error: can\'t find file or read data")
else:
print ("written content in the file successfully")
fh.close()
以上程序输出结果:
written content in the file successfully
实例 下面是简单的例子,它打开一个文件,在该文件中的内容写入内容,但文件没有写入权限,发生了异常:
#!/usr/bin/python3
try:
fh = open("testfile", "r")
fh.write("this is my test file for exception handling!!")
except ioerror:
print ("error: can\'t find file or read data")
else:
print ("written content in the file successfully")
以上代码会执行结果如下
error: can't find file or read data
使用except而不带任何异常类型
你可以不带任何异常类型使用except,如下实例:
try:
you do your operations here;
......................
except:
if there is any exception, then execute this block.
......................
else:
if there is no exception then execute this block.
以上方式try-except
语句捕获所有发生的异常。但这不是一个很好的方式,我们不能通过该程序识别出具体的异常信息。因为它捕获所有的异常。
使用except而带多种异常类型
你也可以使用相同的except语句来处理多个异常信息,如下所示:
try:
you do your operations here;
......................
except(exception1[, exception2[,...exceptionn]]]):
if there is any exception from the given exception list,
then execute this block.
......................
else:
if there is no exception then execute this block.
try-finally 语句
try-finally 语句无论是否发生异常都将执行最后的代码。
try:
you do your operations here;
......................
due to any exception, this may be skipped.
finally:
this would always be executed.
......................
实例
#!/usr/bin/python3
try:
fh = open("testfile", "w")
fh.write("this is my test file for exception handling!!")
finally:
print ("error: can\'t find file or read data")
如果打开的文件没有可写权限,输出如下所示:
error: can't find file or read data
同样的例子也可以写成如下方式:
#!/usr/bin/python3
try:
fh = open("testfile", "w")
try:
fh.write("this is my test file for exception handling!!")
finally:
print ("going to close the file")
fh.close()
except ioerror:
print ("error: can\'t find file or read data")
当在try块中抛出一个异常,立即执行finally块代码。
finally块中的所有语句执行后,异常被再次触发,并执行except块代码。
参数的内容不同于异常。
异常的参数
一个异常可以带上参数,可作为输出的异常信息参数。
你可以通过except语句来捕获异常的参数,如下所示:
try:
you do your operations here;
......................
except exceptiontype, argument:
you can print value of argument here...
变量接收的异常值通常包含在异常的语句中。在元组的表单中变量可以接收一个或者多个值。
元组通常包含错误字符串,错误数字,错误位置。
实例 以下为单个异常的实例:
#!/usr/bin/python3
# 定义函数.
def temp_convert(var):
try:
return int(var)
except valueerror, argument:
print ("the argument does not contain numbers\n", argument)
# 调用自定义的函数
temp_convert("xyz");
以上程序执行结果如下:
the argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
触发异常
我们可以使用raise语句自己触发异常
raise语法格式如下:
raise [exception [, args [, traceback]]]
语句中 exception 是异常的类型(例如,nameerror)参数标准异常中任一种,args 是自已提供的异常参数。
最后一个参数是可选的(在实践中很少使用),如果存在,是跟踪异常对象。
实例 一个异常可以是一个字符串,类或对象。 python的内核提供的异常,大多数都是实例化的类,这是一个类的实例的参数。
定义一个异常非常简单,如下所示:
def functionname( level ):
if level < 1:
raise exception("invalid level!", level)
# 触发异常后,后面的代码就不会再执行
注意:为了能够捕获异常,"except"语句必须有用相同的异常来抛出类对象或者字符串。
例如我们捕获以上异常,"except"语句如下所示:
try:
business logic here...
except "invalid level!":
exception handling here...
else:
rest of the code here...
实例
#!/usr/bin/python3
# 定义函数
def mye( level ):
if level < 1:
raise exception,"invalid level!"
# 触发异常后,后面的代码就不会再执行
try:
mye(0) # 触发异常
except exception,err:
print (1,err)
else:
print (2)
执行以上代码,输出结果为:
1 invalid level!
用户自定义异常
通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自exception类,通过直接或间接的方式。
以下为与runtimeerror相关的实例,实例中创建了一个类,基类为runtimeerror,用于在异常触发时输出更多的信息。
在try语句块中,用户自定义的异常后执行except块语句,变量 e 是用于创建networkerror类的实例。
class networkerror(runtimeerror):
def __init__(self, arg):
self.args = arg
在你定义以上类后,你可以触发该异常,如下所示:
try:
raise networkerror("bad hostname")
except networkerror,e:
print (e.args)