如何解决如果发生异常,如何确保 try/except 循环不会执行所有内容?
假设我有这个代码:
<xsl:template match="tei:seg[tei:pb | tei:lb] | tei:seg//*[tei:pb | tei:lb]">
<xsl:copy>
<xsl:for-each-group select="node()" group-adjacent="boolean(self::text()[not(normalize-space())]|self::tei:pb|self::tei:lb)">
<xsl:choose>
<xsl:when test="current-grouping-key() and current-group()[self::tei:pb|self::tei:lb]">
<xsl:sequence select="current-group()[not(self::text())]"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates select="current-group()"/>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each-group>
</xsl:copy>
</xsl:template>
我想要发生的,是执行函数,但是如果发生错误,根本不执行函数。我不知道这对于 def my_func():
print("Hello World") # <-- This should work
print(x) # <-- This should NOT work,since x is undefined
try:
my_func()
# However,in my try-except loop,the function is being partially executed.
# I want it so that if there is an error,the function shouldn't execute at all,and nothing should happen
except Exception as e:
print(e)
循环是否可行,因为这样做的目的是执行代码直到出现错误,但可能还有其他一些循环可以实现这一点。
抱歉,我知道这是一个非常初级的问题,我可能应该知道这一点,但我是自学的,从来没有遇到过这个问题,不知道该怎么做才能解决这个问题。谢谢!
解决方法
如前所述,您想要的东西是不可能的。但是,您可以做的是以不同的方式构建代码,以便函数运行需要 x:
def my_func(x):
print("Hello World")
print(x)
my_func(x) # Will raise an error if x is not provided
或者,您可以预先检查您需要的任何变量是否存在:
try:
x
# any other variable you need
# this can also be done inside the function itself (probably better to do that tbh)
my_func()
except NameError as e:
print(e)
我知道未分配的变量可能不是您遇到的确切问题,但无论哪种方式,如果您不希望函数执行重要操作并中途失败,请事先进行一些检查,即使只是在函数内部,以确保它有最好的完成机会。希望这在某种程度上有所帮助,如果这不是您要找的内容,请见谅。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。