[英]Prevent 'try' to catch an exception and pass to the next line in python
[英]Python Try/Catch: simply go to next statement when Exception
假設我有以下Python代碼:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
當x.child_list為None時,第3行可能會出現問題。 這顯然給了我一個TypeError ,說:
'NoneType' Object has no attribute '_____getitem_____'
我想要做的是,每當x.child_list [0]給出一個TypeError時 ,只需忽略該行並轉到下一行,即“ link = x.link ”......
所以我猜是這樣的:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
Except TypeError:
# Pass, Ignore the statement that gives exception..
我應該在Except塊下面放什么? 或者還有其他方法可以做到這一點嗎?
我知道我可以使用如果x.child_list不是None:... ,但我的實際代碼要復雜得多,我想知道是否有更多的pythonic方法來做到這一點
你在想什么是這樣的:
try:
x = some_product()
name = x.name
first_child = x.child_list[0]
link = x.link
id = x.id
except TypeError:
pass
但是,最好在try/catch
塊中盡可能少地放置:
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
pass
link = x.link
id = x.id
但是,你真正應該做的就是完全避免try/catch
,而是做這樣的事情:
x = some_product()
name = x.name
first_child = x.child_list[0] if x.child_list else "no child list!"
# Or, something like this:
# first_child = x.child_list[0] if x.child_list else None
link = x.link
id = x.id
當然,您的選擇最終取決於您期望的行為 - 您是否希望將first_child
保留為未定義,等等。
由於您只想在該行上處理異常,因此只能在那里捕獲它。
x = some_product()
name = x.name
try:
first_child = x.child_list[0]
except TypeError:
first_child = None
link = x.link
id = x.id
當您捕獲異常時直接移出try范圍,更好的解決方案是通過修改該行中的代碼來防止異常發生:
if x.child_list[0] != None:
first_child = x.child_list[0]
希望這可以幫助。
編輯
當你編輯你的問題並且你不想要這個解決方案時,唯一的方法是在該特定行之后立即捕獲異常:
try:
first_child = x.child_list[0]
except TypeError:
pass
當x.child_list為None時,第3行可能會出現問題。 這顯然給了我一個TypeError,說:
我認為以異常方式執行此操作是不好的方法。 str / unicode,list,tuple類型有getitem方法或任何其他自定義類可能包含此方法。 如果您正在尋找僅使用元組/列表的解決方案,此代碼將幫助您:
x = some_product()
name = x.name
first_child = (lambda x: x[0] if isinstance(x, list) or isinstance(x, tuple) else None)(x.child_list)
link = x.link
id = x.id
請閱讀有關格式化python代碼的PEP8。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.