python学习7 - 异常
定义异常
python 用异常对象(exception object)来表示异常情况,遇到错误后,会引发异常,如果异常对象未被捕捉或处理,程序就会用所谓的回溯 (Tracebace)执行终止:
1 >>> 1/0 2 3 Traceback (most recent call last): 4 File "<pyshell#99>", line 1, in <module> 5 1/0 6 ZeroDivisionError: integer division or modulo by zero
raise: 自己引发异常,程序会自动创建实例
1 >>> raise Exception 2 3 Traceback (most recent call last): 4 File "<pyshell#100>", line 1, in <module> 5 raise Exception 6 Exception 7 >>> raise Exception("hahahahahaha") 8 9 Traceback (most recent call last): 10 File "<pyshell#101>", line 1, in <module> 11 raise Exception("hahahahahaha") 12 Exception: hahahahahaha
python 内建的异常类有很多,这些异常类都在exceptions 模块中
1 >>> dir(exceptions) 2 ['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__']
一些重要的异常类
自定义异常类,只要这个异常类 继承 Exception
>>> calss AutoError(Exception):pass
捕捉异常
格式如下:
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except ZeroDivisionError: 6 print "the second number cat't be zero" 7 8 the first Num: 10 9 the second Num: 0 10 the second number cat't be zero
ps:如果没有捕捉异常,它就会被调用他的函数的方法体内的 try 捕捉到,依次类推,也就是说 ,你可以捕捉到在其他人的函数中所引发的异常
多个except:
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except ZeroDivisionError: 6 print "the second number cat't be zero" 7 except TypeError: 8 print "That wasn't a number ,was it"
用一个块捕捉多个异常
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except (ZeroDivisionError,TypeError): 6 print "the numbers was bug"
捕捉对象
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except (ZeroDivisionError,TypeError),e: # 在python 3.0 中,格式为except (ZeroDivisionError,TypeError) as e
6 print e
全捕捉 --任何异常都不放过,呵呵
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except : 6 print "hahaha"
else -- 在没有捕捉到异常情况下 出发
1 try: 2 x = input("the first Num: ") 3 y = input("the second Num: ") 4 print x/y 5 except : 6 print "hahaha" 7 else: 8 print "it's ok"
Finally -- 在可能的异常后进行清理,与 try 联合使用
1 try: 2 1/0 3 except: 4 print "err" 5 else: 6 print "it's ok" 7 finally: 8 print "Cleaning up" 9 10 >>> 11 err 12 Cleaning up