简体   繁体   English

python 中嵌套 try-except 中的错误处理

[英]Error Handling in Nested try-except in python

The piece of code i have looks like this:我的代码如下所示:

try:
    funcProneToError()
    #codeBlock1
except:
    #errorMessage

def funcProneToError():
    try:
       #raise error
    except:
       #erorMessage

Now the problem is that if an error is raised in funcProneToError(), the code skips codeBlock1 and prints error message twice.现在的问题是,如果在 funcProneToError() 中出现错误,代码会跳过 codeBlock1 并打印两次错误消息。 is there any way to bypass this?有没有办法绕过这个? iwant to be able to run codeblock1 even if an error is detected in the function.即使在 function 中检测到错误,我也希望能够运行 codeblock1。

Also im coming here after a really long time so ignore any formatting mishaps.我也在很长一段时间后来到这里,所以请忽略任何格式错误。

try:
    funcProneToError()
except:
    #errorMessage
finally:
    #codeBlock1

def funcProneToError():
    try:
       #raise error

(1) Your code handles the exception twice therefore the error message is printed twice. (1) 您的代码两次处理异常,因此错误消息被打印两次。

Remove the except block in funcProneToError().删除 funcProneToError() 中的 except 块。 funcProneToError() raises an exception and this exception is handled (only once) after the function has been called. funcProneToError() 引发异常,并且在调用 function 之后处理此异常(仅处理一次)。

(2) Use a 'finally' block so that codeBlock1 prints regardless of whether there was an exception raised. (2) 使用“finally”块,以便无论是否引发异常,codeBlock1 都会打印。

I hope this helps: :)我希望这有帮助: :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM