一、异常基础
在编程程序出现bug时一般不会将错误信息显示给用户,而是现实一个提示的页面。
1 try:2 #正常逻辑代码
3 input = raw_input("输入数字:")4 data =int(input)5
6 exceptException,e:7 #逻辑代码块出现错误,
8 print '请输入数字!!!'
两个数字相加异常处理:
1 whileTrue:2 number1 = raw_input('number1:')3 number2 = raw_input('number2:')4 try:5 num1 =int(number1)6 num2 =int(number2)7 res = number1 +number28 printres9 exceptException, e:10 print '出现异常,信息如下:'
11 print e
二、异常种类
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
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
ZeroDivisionError
KeyError
dic = {'k1':123,'k2':321}try:
dic['k3']exceptKeyError,e:print '出现异常,信息如下:'
print e
li = ['gavin-guo']try:
li[100]exceptIndexError,e:print '出现异常,信息如下:'
print e
IndexError
str = 'abc'
try:
int(str)exceptValueError,e:print '出现异常,信息如下:'
print e
ValueError
上述实例异常只能处理指定异常,如果非指定异常则无法处理
str = 'abc'
try:
int(str)exceptIndexError,e:print '出现异常,信息如下:'
print e
出现错误信息了,则应该这样处理.
1 str = 'abc'
2 try:3 int(str)4 exceptIndexError,e:5 print '出现异常,信息如下:'
6 printe7 exceptValueError,e:8 print '出现异常,信息如下:'
9 printe10 exceptKeyError,e:11 print '出现异常,信息如下:'
12 print e
python中有一个异常能捕捉到所有异常:Exception
1 str = 'abc'
2 try:3 int(str)4 exceptException,e:5 print e
三、异常的其他结构
1 try:2 #逻辑代码,连接数据库,执行sql语句
3 pass
4 exceptKeyError,e:5 #异常时,执行该块
6 pass
7 else:8 #逻辑码块中未出现异常执行这里的代码
9 pass
10 finally:11 #永远执行,主代码块执行完之后执行.断开数据库连接,释放资源
12 pass
四、主动触发异常
raise Exception('出现错误')
1 classA:2 defa1(self):3 returnFalse4
5 try:6 a = '1'
7 #a = int(a)
8 re =A()9 ret =re.a1()10 ifret:11 print '成功'
12 else:13 raise Exception() #执行这一行代码,等于直接倒转到下面的except Exception
14 exceptException,e:15 print '出现错误!!'
16 print e
五、自定义异常
自己定义一个异常,然后调用这个异常
1 classGavinerror(Exception):2
3 def __init__(self,date=None):4 self.date =date5 def __str__(self):6 ifself.date:7 returnself.date8 else:9 return 'Gavin error'
10 try:11 raiseGavinerror()12 exceptException,e:13 print e