本文作为自己的学习笔记,已尽力详细描述和准确,难免会出现错误,所以这是一个beta版本。
首先什么是异常,
在python或者程序中,由于语法,逻辑或者系统的错误而导致程序出现错误无法执行,而这个错误就是异常。
异常分为两个阶段:
1,引起异常发生的错误
2,检测(也就是采取措施)阶段
python中的异常分为很多种,常见的有如下异常:
1,NameError
>>> foo
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
foo
NameError: name 'foo' is not defined
2,SyntaxError: Python解释器语法错误
>>> for
SyntaxError: invalid syntax
3,KeyError:请求一个不存在的字典关键字
4,IOError:输入/输出错误
等等。所有错误的分类如下:
-BaseException
|-KeyboardInterrput
|-SystemExit
|-Exception(除了以上连个异常,所有的异常分类到这里)
|-(all other current built-in exceptions)
在python中如何捕获异常
try:
try_suite
except Exception[,reasion]:
except_suite
注意在 except 中的代码块,在异常没有发生时,这些代码块是永远不会到达。
例:
try:
f = open('blah','r')
except IOError, e:
print 'could not open file:',e
同样的情况下,try后面可以跟多个except 来处理不同的异常,当然也可以跟一个来处理同类的异常,语法分别如下:
try:
try_suite
except Exception [,reason1]:
suite_for_exception_Exception1
except Exception [,reason2]:
suite_for_exception_Exception2
:
处理多个异常的except 语句:
try:
try_suite
except (Exception1,Exception2) [,reason1]:
suite_for_exception_Exception1_and_Exception2
例:
import sys
try:
s = raw_input('Enter something -->')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit()
except:
print '\nSome error/exception occurred.'
print 'Done'
例:
def safe_float(obj):
try:
retval= float(obj)
except (ValueError,TrypeError):
retval ='argument must be a number or numeric string'
return retval
另外一个用户是捕获所有的异常,但是我建议这样子做
try:
:
except Exception,e:
suit_Exception
else 子句:
在try 范围中没有异常被检测到时,执行else子句。
例:
import 2rd_party_module
log = open('logfile.txt','w')
try:
3rd_party_module.function()
except:
log.write("*** caught exception in module\n")
else:
log.write("*** no exception caught\n")
finally 子句
try:finally不是用来捕获异常,而是来替代的
try:
try_suite
finally:
finallyu_suite #无论如何都要执行
try-except-else-finally:
try:
try_suite
except Exception1:
suite_for_Exception1
except (Exception2,Exception3,Exception4):
suite_for_Exception_2_3_and4
except Exception5,Argument5:
suite_for_Exception_plus_argument
except:
suite_for_all_other_exceptions
else:
no_exceptions_detected_suite
finally:
always_execute_suite
触发异常
raise
例:
#/usr/bin/env python
try:
assert 1==0,'one does not equal zero siily!'
except AssertionError,arges:
print '%s: %s' %(arges.__class__.__name__,arges)