Python錯誤和異常概念(總)
1. 錯誤和異常的處理方式
常見的錯誤
a:NameError
if True:SyntaxError
f = oepn('1.txt'):IOError
10/0:ZeropisionError
a = int('d'):ValueError
程式運行中斷:KeyboardInterrupt
2.Python-使用try_except處理異常(1)
try: try_suiteexcept Exception [e]: exception_block
try用來捕獲try_suite中的錯誤,並且將錯誤交給except處理
except用來處理異常,如果處理異常和設定捕獲異常一致,使用exception_block處理異常
# case 1try: undefexcept: print 'catch an except'
# case 2try: if undefexcept: print 'catch an except'
--
# case 3try: undefexcept NameError,e: print 'catch an except',e
# case 4try: undefexcept IOError,e: print 'catch an except',e
Example
import randomnum = 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'
3. Python使用try_except處理異常(2)
try: try_suiteexcept Exception1[e]: exception_block1except Exception2[e]: exception_block2except ExceptionN[e]: exception_blockN
4. Python-try_finally使用
try: try_suitefinally: do_finally
5. Python-try-except-else-finally
try: try_suite except: do_except finally: do_finally
6. Python-with_as語句
with context [as var]: with_suite
with語句用來代替try_except_finall語句,使代碼更加簡潔
context運算式返回是一個對象
var用來儲存context返回對象,單個傳回值或者元祖
with_suite使用var變數來對context返回對象進行操作
with語句實質是上下文管理:
上下文管理協議:包含方法__enter__()和__exit()__,支援該協議的對象要實現這兩個方法
上下文管理器:定義執行with語句時要建立的運行時上下文,負責執行with語句塊上下文中的進入與退出操作
進入上下文管理器:調用管理器__enter__方法,如果設定as var語句,var變數接受__enter__()方法傳回值
退出上下文管理器:調用管理器__exit__方法
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_valif __name__ == "__main__": with Mycontex('test context') as f: print f.name f.do_self()
whith語句應用情境:
檔案操作
進程線程之間互斥對象,例如互斥鎖
支援內容相關的其他對象
2. 標準異常和自動以異常
1. Python-assert和raise語句
raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-標準異常和自訂異常
class CustomError(Exception): def __init__(self, info): Exception.__init__(self) self.message = info print id(self) def __str__(self): return 'CustionError:%s' % self.messagetry: raise CustomError('test CustomError')except CustomError, e: print 'ErrorInfo:%d,%s' % (id(e), e)