首先申明下,本文为笔者学习《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、捕捉异常
(1) try/except代码块可以捕捉异常,并在except中处理。 >>> def fun(val1, val2): try: print val1 + val2 except TypeError: print "get except" >>> fun("hello", 13) get except (2) 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 exception3、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 except4、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' objects5、引发异常
(1) raise语句 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抛出一个异常时,会自动调用异常类的构造函数来初始化一个异常实例。 (2) assert语句也可以触发异常。 >>> assert False, "You failed" Traceback (most recent call last): File "<pyshell#65>", line 1, in <module> assert False, "You failed" AssertionError: You failed6、异常信息
异常是一个实例对象,可以打印异常信息。 >>> 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、自定义异常
(1) 自定义异常需要继承Exception >>> class NoSuchMethodException(Exception): pass >>> raise NoSuchMethodException Traceback (most recent call last): File "<pyshell#69>", line 1, in <module> raise NoSuchMethodException NoSuchMethodException (2) 自定义异常定制打印。 >>> 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