Python錯誤與例外概念(總)
1.錯誤與例外的處理方式
a:NameError
if True:SyntaxError
f = oepn('1.txt'):IOError
10/0:ZeropisionError
a = int('d'):ValueError
#程式運作中斷:KeyboardInterrupt
try: try_suite except Exception [e]: exception_block
try用來捕捉try_suite中的錯誤,並且將錯誤交給except處理
except用來處理異常,如果處理異常和設定捕獲異常一致,使用exception_block處理異常
# case 1 try: undef except: print 'catch an except'
# case 2 try: if undef except: print 'catch an except'
case1:可以捕獲異常,因為是運行時錯誤
case2:不能捕獲異常,因為是語法錯誤,運行前錯誤
--
# case 3 try: undef except NameError,e: print 'catch an except',e
# case 4 try: undef except IOError,e: print 'catch an except',e
import random num = random.randint(0, 100) while True: try: guess = int(raw_input("Enter 1~100")) except ValueError, e: print "Enter 1~100" continue if guess > num: print "guess Bigger:", guess elif guess < num: print "guess Smaller:", guess elif guess == num: print "Guess OK,Game Over" break print '\n'
try: try_suite except Exception1[e]: exception_block1 except Exception2[e]: exception_block2 except ExceptionN[e]: exception_blockN
try: try_suite finally: do_finally
try: try_suite except: do_except finally: do_finally
with context [as var]: with_suite
和__exit()__
,支援該協定的物件要實作這兩個方法
方法,如果設定as var語句,var變數接受__enter__()
方法傳回值
方法
class Mycontex(object): def __init__(self, name): self.name = name def __enter__(self): print "__enter__" return self def do_self(self): print "do_self" def __exit__(self, exc_type, exc_val, exc_tb): print "__exit__" print "Error:", exc_type, " info:", exc_val if __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
assert 0, 'test assert'
assert 4==5, 'test assert'
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.message try: raise CustomError('test CustomError') except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)
更多Python錯誤與異常概念相關文章請關注PHP中文網!