异常处理: 这将在本教程所覆盖讲解。这是 Python 提供的标准异常的列表:标准异常
断言: 这将在Python3断言教程覆盖。
标准异常如下列表 -
异常名称
描述
Exception
所有异常的基类
StopIteration
当一个迭代器的 next()方法不指向任何对象时引发
SystemExit
由 sys.exit()函数引发
StandardError
除了StopIteration异常和SystemExit,所有内置异常的基类
ArithmeticError
数值计算所发生的所有错误的基类
OverflowError
当数字类型计算超过最高限额引发
FloatingPointError
当一个浮点运算失败时触发
ZeroDivisonError
当除运算或模零在所有数值类型运算时引发
AssertionError
断言语句失败的情况下引发
AttributeError
属性引用或赋值失败的情况下引发
EOFError
当从 raw_input() 与 input() 函数输入,到达文件末尾时触发
ImportError
当一个 import 语句失败时触发
KeyboardInterrupt
当用户中断程序执行,通常是通过按 Ctrl+c 引发
LookupError
所有查找错误基类
IndexError
KeyError
当在一个序列中没有找到一个索引时引发
当指定的键没有在字典中找到引发
NameError
当在局部或全局命名空间中找不到的标识引发
UnboundLocalError
EnvironmentError
试图访问在函数或方法的局部变量时引发,但没有值分配给它。
Python环境之外发生的所有异常的基类。
IOError
IOError
当一个输入/输出操作失败,如打印语句或 open()函数试图打开不存在的文件时引发
操作系统相关的错误时引发
SyntaxError
IndentationError
当在Python语法错误引发;
没有正确指定缩进引发。
SystemError
当解释器发现一个内部问题,但遇到此错误时,Python解释器不退出引发
SystemExit
当Python解释器不使用sys.exit()函数引发。如果代码没有被处理,解释器会退出。
当操作或函数在指定数据类型无效时引发
ValueError
在内置函数对于数据类型,参数的有效类型时引发,但是参数指定了无效值
RuntimeError
当生成的错误不属于任何类别时引发
NotImplementedError
当要在继承的类来实现,抽象方法实际上没有实现时引发此异常
在Python中断言
断言是一种理智检查,当程序的测试完成,你可以打开或关闭。
断言的最简单的方法就是把它比作 raise-if 语句 (或者更准确,加 raise-if-not 声明). 一个表达式进行测试,如果结果出现 false,将引发异常。
断言是由 assert 语句,在Python中新的关键字,在Python1.5版本中引入使用的关键字。
程序员常常放置断言来检查输入的有效,或在一个函数调用后检查有效的输出。
assert 语句
当它遇到一个断言语句,Python评估计算之后的表达式,希望是 true 值。如果表达式为 false,Python 触发 AssertionError 异常。
断言的语法是 -
assert Expression[, Arguments]
如果断言失败,Python使用 ArgumentExpression 作为AssertionError异常的参数。AssertionError异常可以被捕获,并用 try-except语句处理类似其他异常,但是,如果没有处理它们将终止该程序并产生一个回溯。
示例
这里是一个把从开氏度到华氏度的温度转换函数。
#!/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: 块来保护你的程序。在 try:块之后,包括 except: 语句随后的代码块,作为优雅的处理异常问题。
语法
下面是 try....except...else 块的简单的语法 −
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
以下是有关上述语法几个重要的地方 -
单个 try 语句可以有多个except语句。 当 try 块包含可能抛出不同类型的异常声明这是有用的
也可以提供一个通用的 except 子句来处理任何异常
except子句后,可以包括 else 子句。 如果代码在try:块不引发异常则代码在 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.
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子句
可以使用 finally: 使用 try: 块. finally 块是必须执行,而不管 try 块是否引发异常或没有。try-finally 语句的语法是这样的 -
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
请注意,可以提供 except 子句,或 finally 子句,但不能同时使用。不能用一个 finally 子句中再使用 else 子句 。
示例
#!/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")
fh.close()
如果您没有以写入方式打开文件的权限,那么这将产生以下结果:
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 块。如果在 try-except 语句的下一个更高的层异常被再次引发,并在处理 except 语句外。
异常的参数
异常可以有一个参数,这是有关问题的其他信息的值。参数的内容作为异常而都不太一样。可以通过不同的子句中提供一个变量,如下所示捕获异常参数 -
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here...
如果写代码来处理一个异常,可以使用一个变量按照异常的名称在 except 语句中。 如果要捕捉多个异常,可以使用一个变量后跟一个异常的元组。
该变量接收大多含有异常的原因各种值。变量可以在一个元组的形式以接收一个或多个值。这个元组通常包含错误字符串,错误编号,以及错误位置。
示例
下面是一个异常的例子-
#!/usr/bin/python3
# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, as Argument:
print ("The argument does not contain numbers\n", Argument)
# Call above function here.
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)argument 为异常的参数值。该参数是可选的;如果没有提供,异常的参数是None。
最后一个参数 traceback,也可选的(并在实践中很少使用),并且如果存在的话,是用于异常的回溯对象。
示例
异常可以是一个字符串,一个类或一个对象。大多数Python的异常核心是触发类异常,使用类的一个实例参数的异常。定义新的异常是很容易的,可以按如下做法 -
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
注意:为了捕捉异常,一个“except”语句必须是指出抛出类对象异常或简单的字符串异常。例如,捕获异常上面,我们必须编写 except 子句如下 -
try:
Business Logic here...
except Exception as e:
Exception handling here using e.args...
else:
Rest of the code here...
下面的例子说明如何使用触发异常:
#!/usr/bin/python3
def functionName( level ):
if level <1:
raise Exception(level)
# The code below to this would not be executed
# if we raise the exception
return level
try:
l=functionName(-10)
print ("level=",l)
except Exception as e:
print ("error in level argument",e.args[0])
这将产生以下结果
error in level argument -10
用户定义的异常
Python中,还可以通过内置的异常标准的派生类来创建自己的异常。
这里是关于 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