1. 什么是异常
Python用异常对象(exceptionobject)来表示异常情况,每个异常都是一些类的实例。如果异常对象并未被处理或捕捉,程序就会用回溯(Traceback,一种错误信息)终止执行:
>>> 1/0
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
1/0
ZeroDivisionError: integer divisionor modulo by zero
2. 引发异常—raise语句
为了引发异常,可以使用一个类(Exception类的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例:
>>> raise Exception('出现了异常')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
raise Exception('出现了异常')
Exception: 出现了异常
异常类分为内建的异常类和自定义异常类。内建的异常类都可以再exceptions模块中找到:
>>> import exceptions
>>> dir(exceptions)
['ArithmeticError','AssertionError', 'AttributeError', 'BaseException', 'BufferError','BytesWarning', 'DeprecationWarning', 'EOFError', 'EnvironmentError','Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError','ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError','KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError','NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning','ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError','StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit','TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError','UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError','UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError','ZeroDivisionError', '__doc__', '__name__', '__package__']
3. 捕捉异常—try/except
1)
#捕捉了两个异常(异常类型作为元组列出),统一进行处理
try:
x=input('x=')
y=input('y=')
printx/y
except(ZeroDivisionError,TypeError):
print'出现了异常'
2)
#捕捉了两个异常(异常类型作为元组列出),且将异常信息打印出来
#出现异常后,程序继续运行,不会终止
try:
x=input('x=')
y=input('y=')
printx/y
except (ZeroDivisionError,TypeError),e:
printe
3)
#捕捉所有的异常情况,使用空的except子句来捕捉所有Exception类的异常
try:
x=input('x=')
y=input('y=')
printx/y
except:
print'出现了异常'
4)
#捕捉所有的异常情况,且将异常信息打印出来
While True:
try:
x=input('x=')
y=input('y=')
print x/y
except Exception,e:
print'Invalid input',e
else:
break
5)
#可以综合运用try、except、else和finally(进行清理)
try:
1/0
except NameError:
print 'Unknown variable'
else:
print 'That went well'
finally:
print 'Cleaning up'