![](/img/trans.png)
[英]How to continue try block when on exception with keyerror in python
[英]How to continue with next line in a Python's try block?
例如
try:
foo()
bar()
except:
pass
當foo函數引發異常時,如何跳到下一行(bar)並執行它?
從try
塊中取出bar()
:
try:
foo()
except:
pass
bar()
順便說一下, except
條款except
,請注意全部。 更喜歡有選擇地捕獲您知道可以處理/忽略的異常。
如果對bar
的調用在try
-block中,則無法完成。 您必須將調用置於try-except塊之外,或使用else
:
try:
foo()
except:
pass
else:
bar()
如果bar
也可能拋出異常,則必須使用單獨的try
塊作為bar
。
這不是try / except塊的預期方式。 如果即使foo()
失敗也應該執行bar()
,你應該把它們放在自己的try / except塊中:
try:
foo()
except:
pass # or whatever
try:
bar()
except:
pass # or whatever
如果您只有兩個函數foo()bar(),請檢查其他解決方案。 如果你需要運行很多行,請嘗試類似這樣的例子:
def foo():
raise Exception('foo_message')
def bar():
print'bar is ok'
def foobar():
raise Exception('foobar_message')
functions_to_run = [
foo,
bar,
foobar,
]
for f in functions_to_run:
try:
f()
except Exception as e:
print '[Warning] in [{}]: [{}]'.format(f.__name__,e)
結果:
[Warning] in [foo]: [foo_message]
bar is ok
[Warning] in [foobar]: [foobar_message]
如果您希望兩個函數的異常都由相同的except子句處理,那么使用內部try / finally塊:
try:
try:
foo()
finally:
bar()
except Exception:
print 'error'
如果foo()
存在異常,則執行第一個bar()
,然后執行except子句。
但是,將最少量的代碼放在try塊中通常是一種好習慣,因此每個函數的單獨異常處理程序可能是最好的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.