Python 尝试/捕获 : simply go to next statement when Exception

标签 python exception

假设我有以下 Python 代码:

x = some_product()
name        = x.name
first_child = x.child_list[0]
link        = x.link
id          = x.id

x.child_listNone 时,第 3 行可能会出现问题。这显然给了我一个TypeError,表示:

'NoneType' Object has no attribute '_____getitem_____'

我想做的是,每当 x.child_list[0] 给出一个 TypeError 时,只需忽略该行并转到下一行,即“< strong>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 block 下放什么? 还是有其他方法可以做到这一点?

我知道我可以使用 If x.child_list is not 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 block 中放置尽可能少的内容:

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 未定义,等等。

关于Python 尝试/捕获 : simply go to next statement when Exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22736412/

相关文章:

python - 我如何观看python源代码文件并在保存时重新启动?

c++ - 异常未在 try catch block 中捕获

异常模式下的 PHP PDO - 仍然需要检查执行函数(和其他函数)的返回?

java - 在 Java 中拯救被吞噬的异常

python - 如何实现神经网络剪枝?

python - Pandas :将时间间隔整数转换为时间

python - Python 中导入模块和从模块导入之间存在差异的问题

python套接字错误: AF_INET address must be tuple,不是str

exception - 尝试更新 ProductPO 自定义属性时出现 OCAException

node.js - Deno:如何处理异常