Python中的所有實(shí)例必須是從BaseException派生的類的實(shí)例。通過(guò)子類不相關(guān)的兩個(gè)異常類,即使它們具有相同的名稱,也永遠(yuǎn)不會(huì)等效。內(nèi)置異常可以由解釋器或內(nèi)置函數(shù)生成。 錯(cuò)誤發(fā)生時(shí),Python中會(huì)引發(fā)一些內(nèi)置的異常。可以使用local()內(nèi)置函數(shù)來(lái)查看這些內(nèi)置異常,如下所示: '__ builtins__'] > locals()[ 這將返回內(nèi)置異常,函數(shù)和屬性的字典。 基類 以下異常通常用作其他異常的基類。 1、exception BaseException
try: ... except SomeException: tb = sys.exc_info()[2] raise OtherException(...).with_traceback(tb) 2、exception Exception 3、exception ArithmeticError
范例: try: a = 10/0 print a except ArithmeticError: print "此語(yǔ)句引發(fā)算術(shù)異常." else: print "Success." 輸出: 此語(yǔ)句引發(fā)算術(shù)異常。 4、exception BufferError 5、exception LookupError
范例: try: a = [1, 2, 3] print a[3] except LookupError: print "索引越界錯(cuò)誤." else: print "Success" 輸出: 索引越界錯(cuò)誤. 具體例外 以下異常是通常引發(fā)的異常。 異常AssertionError 范例: assert False,“斷言失敗” 輸出: Traceback (most recent call last): File "exceptions_AssertionError.py", line 12, in assert False, 'The assertion failed' AssertionError: The assertion failed exception AttributeError 范例: class Attributes(object): pass object = Attributes() print object.attribute 輸出: Traceback (most recent call last): File "d912bae549a2b42953bc62da114ae7a7.py", line 5, in print object.attribute AttributeError: 'Attributes' object has no attribute 'attribute' exception EOFError 范例: while True: data = raw_input('輸入名稱: ') print 'Hello ', data
輸出: 輸入名稱:Hello 軟件測(cè)試test 輸入名稱:Traceback(最近一次通話): 文件“ exceptions_EOFError.py”,第13行, 數(shù)據(jù)= raw_input('輸入名稱:') EOFError:讀取行時(shí)出現(xiàn)EOF 異常FloatingPointError 范例: import math print math.exp(1000) 輸出: Traceback (most recent call last): File "", line 1, in FloatingPointError: in math_1 異常GeneratorExit 范例: def my_generator(): try: for i in range(5): print 'Yielding', i yield i except GeneratorExit: print 'Exiting early' g = my_generator() print g.next() g.close() 輸出: Yielding 0 0 Exiting early 異常ImportError 范例: import module_does_not_exist 輸出: Traceback (most recent call last): File "exceptions_ImportError_nomodule.py", line 12, in import module_does_not_exist ImportError: No module named module_does_not_exist 范例: from exceptions import Userexception 輸出: Traceback (most recent call last): File "exceptions_ImportError_missingname.py", line 12, in from exceptions import Userexception ImportError: cannot import name Userexception exception ModuleNotFoundError exception IndexError 范例: array = [ 0, 1, 2 ] print array[3] 輸出: Traceback (most recent call last): File "exceptions_IndexError.py", line 13, in print array[3] IndexError: list index out of range exception KeyError 范例: array = { 'a':1, 'b':2 } print array['c'] 輸出: Traceback (most recent call last): File "exceptions_KeyError.py", line 13, in print array['c'] KeyError: 'c' exception KeyboardInterrupt 范例: try: print '按Return或Ctrl-C:', ignored = raw_input() except Exception, err: print '捕獲到異常:', err except KeyboardInterrupt, err: print '捕捉到鍵盤中斷' else: print '沒有錯(cuò)誤' 輸出: 按Return鍵或Ctrl-C鍵:^ 捕捉到鍵盤中斷 exception MemoryError 范例: def fact(a): factors = [] for i in range(1, a+1): if a%i == 0: factors.append(i) return factors num = 600851475143 print fact(num) 輸出: Traceback (most recent call last): File "4af5c316c749aff128df20714536b8f3.py", line 9, in print fact(num) File "4af5c316c749aff128df20714536b8f3.py", line 3, in fact for i in range(1, a+1): MemoryError 異常NameError 范例: def func(): print ans func() 輸出: Traceback (most recent call last): File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 4, in func() File "cfba0a5196b05397e0a23b1b5b8c7e19.py", line 2, in func print ans NameError: global name 'ans' is not defined 異常NotImplementedError 范例: class BaseClass(object): """定義接口""" def __init__(self): super(BaseClass, self).__init__() def do_something(self): """接口,未實(shí)現(xiàn)""" raise NotImplementedError(self.__class__.__name__ + '.do_something') class SubClass(BaseClass): """實(shí)現(xiàn)接口""" def do_something(self): """真的做了些什么""" print self.__class__.__name__ + ' doing something!' SubClass().do_something() BaseClass().do_something() 輸出: Traceback (most recent call last): File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 16, in BaseClass().do_something() File "b32fc445850cbc23cd2f081ba1c1d60b.py", line 7, in do_something raise NotImplementedError(self.__class__.__name__ + '.do_something') NotImplementedError: BaseClass.do_something 異常OSError([arg]) 范例: Traceback (most recent call last): File "442eccd7535a2704adbe372cb731fc0f.py", line 4, in print i, os.ttyname(i) OSError: [Errno 25] Inappropriate ioctl for device exception OverflowError 范例: import sys print '正則整數(shù): (maxint=%s)' % sys.maxint try: i = sys.maxint * 3 print '沒有溢出 ', type(i), 'i =', i except OverflowError, err: print '溢出于 ', i, err print print '長(zhǎng)整數(shù):' for i in range(0, 100, 10): print '%2d' % i, 2L ** i print print '浮點(diǎn)值:' try: f = 2.0**i for i in range(100): print i, f f = f ** 2 except OverflowError, err: print '之后溢出 ', f, err 輸出: 9223372036854775807) = 27670116110564327421 =
長(zhǎng)整數(shù): 0 1 10 1024 20 1048576 30 1073741824 40 1099511627776 50 1125899906842624 60 1152921504606846976 80 1208925819614629174706176 90 1237940039285380274899124224
浮點(diǎn)值: 0 1.23794003929e + 27 1 + 1.53249554087e 54 2 2.34854258277e + 108 3 5.5156522631e + 216 + 216之后溢出(34,'數(shù)值結(jié)果超出范圍') 異常RecursionError 異常ReferenceError 范例: import gc import weakref class Foo(object): def __init__(self, name): self.name = name def __del__(self): print '(Deleting %s)' % self obj = Foo('obj') p = weakref.proxy(obj) print '之前:', p.name obj = None print '之后:', p.name 輸出: BEFORE: obj (Deleting ) AFTER:
Traceback (most recent call last): File "49d0c29d8fe607b862c02f4e1cb6c756.py", line 17, in print 'AFTER:', p.name ReferenceError: weakly-referenced object no longer exists exception RuntimeError 異常StopIteration 范例: Arr = [3, 1, 2] i=iter(Arr) print i print i.next() print i.next() print i.next() print i.next() 輸出: 3 1 2
Traceback (most recent call last): File "2136fa9a620e14f8436bb60d5395cc5b.py", line 8, in print i.next() StopIteration 異常SyntaxError 范例: try: print eval('軟件測(cè)試test') except SyntaxError, err: print 'Syntax error %s (%s-%s): %s' % \ (err.filename, err.lineno, err.offset, err.text) print err 輸出: Syntax error (1-9): 軟件測(cè)試test invalid syntax (, line 1) 異常SystemError exception SystemExit 異常TypeError 范例: arr = ('tuple', ) + 'string' print arr 輸出: Traceback (most recent call last): File "30238c120c0868eba7e13a06c0b1b1e4.py", line 1, in arr = ('tuple', ) + 'string' TypeError: can only concatenate tuple (not "str") to tuple exception UnboundLocalError 范例:
def global_name_error(): print 未知的全局名 def unbound_local(): local_val = local_val + 1 print 本地名稱 try: global_name_error() except NameError, err: print '全局名稱錯(cuò)誤:', err try: unbound_local() except UnboundLocalError, err: print '本地名稱錯(cuò)誤:', err 輸出: Global name error: global name '全局名稱錯(cuò)誤' is not defined Local name error: local variable '本地名稱' referenced before assignment 異常UnicodeError 異常ValueError 范例: print int('a') 輸出: Traceback (most recent call last): File "44f00efda935715a3c5468d899080381.py", line 1, in print int('a') ValueError: invalid literal for int() with base 10: 'a' exception ZeroDivisionError 范例: print 1/0 輸出: Traceback (most recent call last): File "c31d9626b41e53d170a78eac7d98cb85.py", line 1, in print 1/0 ZeroDivisionError: integer division or modulo by zero |
|
來(lái)自: 軟件測(cè)試test > 《python自動(dòng)化》