首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
每当Python运行时程序发生错误,Python会引发异常。可以在程序中捕捉和响应异常,或者忽略异常。
1. 默认异常处理
默认异常处理就是打印错误信息
>>> def fun(val1, val2): # 定义一个加法函数
return val1 + val2
>>> fun("Hello World!", 13) # 字符串和数字不能相加
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
fun("Hello World!", 13)
File "<pyshell#2>", line 2, in fun
return val1 + val2
TypeError: cannot concatenate 'str' and 'int' objects
2. 捕捉异常
try/except
代码块可以捕捉异常,并在except
中处理。
>>> def fun(val1, val2):
try:
print val1 + val2
except TypeError:
print "get except"
>>> fun("hello", 13)
get except
except
可以捕捉一个或多个异常
>>> def fun():
try:
action() # 某个方法
except TypeError: # 捕捉异常
print "get TypeError"
except IndexError, KeyError: # 可以同时捕捉多个异常
print "get IndexError or KeyError"
except: # 捕捉任意异常,类似于except Exception
print "get exception"
>>> def action(): # TypeError
"Hello World" + 5
>>> fun()
get TypeError
>>> def action(): # IndexError
"hello"[10]
>>> fun()
get IndexError or KeyError
>>> def action(): # ZeroDivisionError
1/0
>>> fun()
get exception
3. else语句
else
语句与except
配合使用,如果没有遇到异常发生,执行else
语句。
else
语句至少要有一个except
语句。
>>> def fun(val1, val2):
try:
print val1 + val2
except TypeError:
print "get except"
else:
print "no error occur"
>>> fun(3, 4) # 正常运行,调用else语句
7
no error occur
>>> fun("hello", 5) # 发生异常,不调用else语句
get except
4. finally语句
不管try
代码中是否发生异常,finally
语句都会执行。
>>> def fun(val1, val2):
try:
return val1 + val2
finally:
print "In finally"
>>> fun(3, 4) # 正常运行,调用finally语句
In finally
7
>>> fun("Hello", 4) # 发生异常,同样调用finally语句
In finally
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
fun("Hello", 4)
File "<pyshell#25>", line 3, in fun
return val1 + val2
TypeError: cannot concatenate 'str' and 'int' objects
5. 引发异常
raise
语句可以抛出一个异常,或者一个异常实例。
>>> raise TypeError
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
raise TypeError
TypeError
>>> raise TypeError("TypeError instance")
Traceback (most recent call last):
File "<pyshell#64>", line 1, in <module>
raise TypeError("TypeError instance")
TypeError: TypeError instance
raise
抛出一个异常时,会自动调用异常类的构造函数来初始化一个异常实例。
assert
语句也可以触发异常。
>>> assert False, "You failed"
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
assert False, "You failed"
AssertionError: You failed
6. 异常信息
异常是一个实例对象,可以打印异常信息。
>>> try:
raise TypeError("TypeError instance")
except TypeError as err:
print err.__class__
print err.args
import sys
print sys.exc_info()[0]
<type 'exceptions.TypeError'>
('TypeError instance',)
<type 'exceptions.TypeError'>
7. 自定义异常
自定义异常需要继承Exception
>>> class NoSuchMethodException(Exception):
pass
>>> raise NoSuchMethodException
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
raise NoSuchMethodException
NoSuchMethodException
自定义异常定制打印。
>>> class NoSuchMethodException(Exception):
def __init__(self, filename, function):
self.filename = filename
self.function = function
def __str__(self):
return "NoSuchMethod %s at %s" % (self.function, self.filename)
>>> try:
raise NoSuchMethodException("test.py", "indexAt")
except Exception as excpt:
print excpt
NoSuchMethod indexAt at test.py
相关文章
Python 数字类型(一)
Python 布尔型(二)
Python 字符串(三)
Python 列表(四)
Python 字典(五)
Python 元组(六)
Python 集合(七)
Python 变量和作用域(八)
Python 语句(九)
Python 函数(十)
Python 类(十一)
Python 模块(十二)
Python 文档(十三)
Python 文件(十四)
Python 异常(十五)
Python 运算符重载(十六)