python 異常知識點

2022-02-04 18:39:06 字數 2329 閱讀 9472

python 在3.0 之後引入了raise from 表示式:

raise exception from otherexception

當使用該語法時,第二個表示式指定了另乙個異常類或例項,它會附加到引發異常的__cause__屬性

注意:python3.0不再支援raise exc,args形式,而該形式在python2.6中仍然可用,在python3.0中,使用 raise exc(args)呼叫。

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:

defmessage(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

raise

typeerror

typeerror

nning',

'test2')('

raise an exception!

', '

exceptions.typeerror

'>)

知識點小結 異常

1.異常 try catch 錯誤 error 無法解決 1.try catch 程式的流程是 執行到try塊中,如果有異常丟擲,則轉到catch塊去處理。然後執行catch塊後面的語句 2.try catch finally 程式的流程是 執行到try塊中,如果有異常丟擲,則轉到catch塊,ca...

Python丟擲引發異常 raise 知識點總結

python中try塊可以捕獲測試 塊中的錯誤。except塊可以處理錯誤。finally塊可以執行 而不管try 和except塊的結果如何。本文主要介紹python 丟擲引bgjjd發異常 raise python 常用術語 丟擲引發異常 raise bgjjd 作為python開發人員,可以在...

python大一知識點 python知識點複習

放假歸來,這幾天複習了一下好久不用的python,總結了一下知識點。語法基礎tuple與list的異同都由多個元素組成 tuple由 組成,list由組成 tuple不可變,list可變 tuple表示的是一種結構,而list表示的是多個事物的集合 tuple操作比list快 字串用法要點 轉義符和...