raise from
python 在3.0 之后引入了raise from 表達式:
raise exception from otherexception
當使用該語法時,第二個表達式指定了另一個異常類或實例,它會附加到引發異常的__cause__屬性
注意:
python3.0不再支持raise Exc,Args形式,而該形式在Python2.6中仍然可用,在Python3.0中,使用 raise Exc(Args)調用。
with as
with語句格式:
with expression [as variable]:
with-block
variable是expression執行后返回的對象引用。
with as 作用是先執行啟動程序,然后執行代碼塊,執行終止程序代碼,無論該代碼塊是否引發異常。
例如:
myfile = open(r'C:\misc\data') try: for line in myfile: print(line) finally: myfile.close
可以使用:
with open(r'C;\misc\data') as myfile: for line in myfile: print(line)
自定義環境管理協議
就是自定義可以接入with語句的對象。
with語句實際工作方式:
1、計算表達式,所得到的對象稱為環境管理器,它必須有__enter__和__exit__方法。
2、環境管理器的__enter方法被調用,如果as語句存在,則返回值會被賦值給as子句中的變量
3、代碼塊中嵌套代碼會被執行。
4、如果with引發異常,__exit__(type, value, traceback)方法會被調用,如果此方法返回值為假,則異常會被重新觸發,否則,異常會被終止。正常情況下,應該重新觸發異常,這樣的話才能傳遞到with語句之外。
5、如果with代碼塊沒有引發異常,__exit__方法依然會被調用,其type、value、traceback都會以None傳遞。
例:
class TraceBlock: def message(self, arg): print('running',arg) def __enter__(self): print('starting with block') return self def __exit__(self, exc_type, exc_value, exc_th): if exc_type is None: print('exited normally\n') else: print('raise an exception!', exc_type) return False with TraceBlock() as action: action.message('test 1') print('reached') with TraceBlock() as action: action.message('test2') raise TypeError print('not reached')
執行結果:
starting with block ('running', 'test 1') reached exited normally starting with block ('ruTraceback (most recent call last): File "D:\workspace\aptana\pythonTest\test\com\cy\cyg\TraceBlock.py", line 27, in <module> raise TypeError TypeError nning', 'test2') ('raise an exception!', <type 'exceptions.TypeError'>)