异常
Python用异常对象(exception object)来表示异常状况。遇到错误后,会引起异常。若是异常对象并未被处理或捕捉,程序就会用所谓的回溯(Traceback,一种错误信息)终止执行。函数
一、raise语句
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exceptionthis
>>> raise Exception("error error error!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: error error error!对象
二、重要的内建异常类:索引
Exception : 全部异常的基类
AttributeError: 特性引用或赋值失败时引起
IOError: 试图打开不存在的文件(包括其余状况)时引起
IndexError: 在使用序列中不存在的索引时引起
KeyError:在使用映射序列中不存在的键时引起
NameError:在找不到名字(变量)时引起
SyntaxError:在代码为错误形式时引起
TypeError:在内建操做或者函数应用于错误类型的对象时引起
ValueError:在内建操做或者函数应用于正确类型的对象, 可是该对象使用不合适的值时引起
ZeroDibivionError:在除法或者模除操做的第二个参数为0时引起input
三、自定义异常类
class SubclassException(Exception):passio
四、捕捉异常
使用 try/except
>>> try:
... x = input('Enter the first number:')
... y = input('Enter the second number:')
... print x/y
... except ZeroDivisionError:
... print "the second number can't be zero!"
...
Enter the first number:2
Enter the second number:0
the second number can't be zero!ast
五、捕捉对象class
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print x/y
except (ZeroDivisionError, TypeError), e:
print e变量
# 运行输出
Enter the first number:4
Enter the second number:'s'
unsupported operand type(s) for /: 'int' and 'str'module
六、所有捕捉
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print x/y
except:
print "Something was wrong"
七、try/except else:
else在没有异常引起的状况下执行
try:
x = input('Enter the first number:')
y = input('Enter the second number:')
print x/y
except:
print "Something was wrong"
else:
print "this is else"
# 执行后的输出结果
Enter the first number:3
Enter the second number:2
1
this is else
八、finally
能够用在可能异常后进行清理,和try联合使用
try: x = input('Enter the first number:') y = input('Enter the second number:') print x/y except (ZeroDivisionError, TypeError), e: print e else: print "this is else" finally: print "this is finally"