[英]what is the correct way to handle a caught exception and raise it outside of try block
[英]What is correct way to use try/catch block in case of for loop?
我對應該如何將try-catch塊與for循環一起使用感到困惑。 有什么我們應該遵循的標准。 這些是一些示例代碼。 哪一種是首選方法?
def func1():
try:
for i in range():
do_something()
except:
print(error)
def func1():
for i in range():
try:
do_something()
except:
print(error)
或在使用多個for循環的情況下:
def func3():
try:
for i in range():
for j in range():
do_something()
except:
print(error)
def func4():
for i in range():
for j in range():
try:
do_something()
except:
print(error)
根據條件,如果您有多個for循環,並且內部循環中的函數引發錯誤,是否要繼續為其他輸入運行for循環,還是要完全停止for循環執行。
如果您想繼續運行循環,那么將try catch放入for循環中是很有意義的,如下所示,因此您仍然可以繼續循環
與往常一樣,您可以在任何一種嘗試捕獲邏輯中都具有finally
條件,這可能會對您有所幫助!
def func4():
for i in range():
for j in range():
try:
do_something()
except:
print(error)
但是,如果您想停止循環以防發生異常,則將try-catch保留在循環之外很有意義
def func3():
try:
for i in range():
for j in range():
do_something()
except:
print(error)
第一種方法確實有一個警告,如果循環運行了100次,並且拋出了10次異常,也許您每次都需要以不同的方式處理它或抑制它,並且您不確定是否會有更多的異常會發生一旦有更多的循環運行,就被拋棄。 如果正在處理列表列表,並且某些子列表中包含不良元素,而您想忽略它們並保留res.t,那么在for循環中捕獲異常是有益的一個示例可能是。
而在第二種方法中,您只是在第一個異常上停止並放棄循環,如果要循環的數據量很大,並且每次都需要重新啟動循環,則這可能會很糟糕,但是如果您要循環,則可能會有所幫助您想在看到第一個錯誤時更正數據集,然后再次運行它!
這取決於您的情況。
如果需要完成成功操作才能繼續,則可能需要將try / catch置於循環之外 。
如果循環中的結果不會互相影響,則可以將try / catch 放入循環中。
例如,從網站下載內容(錯誤時循環不會中斷):
contents = []
for i in range(100):
try:
contents.append(requests.get("http://example.com/%d.html" % i))
except:
print("page %d is not available.", i)
更新游戲或應用程序(出錯時中斷循環):
updateList = ["File1.jpg", "File2.jpg"]
try:
for file in updateList:
res = requests.get("http://example.com/%s" % file)
except:
print("Update has failed, application cannot continue.")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.