[英]How to continue with next line in a Python's try block?
eg 例如
try:
foo()
bar()
except:
pass
When foo function raise an exception, how to skip to the next line (bar) and execute it? 当foo函数引发异常时,如何跳到下一行(bar)并执行它?
Take bar()
out of the try
block: 从
try
块中取出bar()
:
try:
foo()
except:
pass
bar()
Btw., watch out with catch-all except
clauses. 顺便说一下,
except
条款except
,请注意全部。 Prefer to selectively catch the exceptions that you know you can handle/ignore. 更喜欢有选择地捕获您知道可以处理/忽略的异常。
Can't be done if the call to bar
is inside the try
-block. 如果对
bar
的调用在try
-block中,则无法完成。 Either you have to put the call outside of the try-except block, or use the else
: 您必须将调用置于try-except块之外,或使用
else
:
try:
foo()
except:
pass
else:
bar()
If bar
might throw an exception as well, you have to use a separate try
block for bar
. 如果
bar
也可能抛出异常,则必须使用单独的try
块作为bar
。
That is not the intended way for try/except blocks to be used. 这不是try / except块的预期方式。 If
bar()
should be executed even if foo()
fails, you should put each in its own try/except block: 如果即使
foo()
失败也应该执行bar()
,你应该把它们放在自己的try / except块中:
try:
foo()
except:
pass # or whatever
try:
bar()
except:
pass # or whatever
If you have just two functions, foo() bar(), check the other solutions. 如果您只有两个函数foo()bar(),请检查其他解决方案。 If you need to run A LOT of lines, try something like this example:
如果你需要运行很多行,请尝试类似这样的例子:
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)
Result: 结果:
[Warning] in [foo]: [foo_message]
bar is ok
[Warning] in [foobar]: [foobar_message]
If you want exceptions from both functions to be handled by the same except clause, then use an inner try/finally block: 如果您希望两个函数的异常都由相同的except子句处理,那么使用内部try / finally块:
try:
try:
foo()
finally:
bar()
except Exception:
print 'error'
If there is an exception in foo()
, first bar()
will be executed, then the except clause. 如果
foo()
存在异常,则执行第一个bar()
,然后执行except子句。
However, it's generally good practice to put the minimum amount of code inside a try block, so a separate exception handler for each function might be best. 但是,将最少量的代码放在try块中通常是一种好习惯,因此每个函数的单独异常处理程序可能是最好的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.