Python:通过具有多个Excepts的TryExcept块传播异常

Python:通过具有多个Excepts的TryExcept块传播异常,第1张

概述有没有办法将try / except块中的异常从一个传播到另一个除外?我想捕获一个特定的错误,然后进行一般的错误处理.“raise”允许异常“冒泡”到外部try / except,但不在try / except块内引发错误.理想情况应该是这样的:import logging def getList(): try: newList =

有没有办法将try / except块中的异常从一个传播到另一个除外?

我想捕获一个特定的错误,然后进行一般的错误处理.

“raise”允许异常“冒泡”到外部try / except,但不在try / except块内引发错误.

理想情况应该是这样的:

import loggingdef getList():    try:        newList = ["just","some","place","holders"]        # Maybe from something like: newList = untrustedGetList()        # Faulty List Now throws IndexError        someitem = newList[100]        return newList    except IndexError:        # For deBUGging purposes the content of newList should get logged.        logging.error("IndexError occured with newList containing: \n%s",str(newList))    except:        # General errors should be handled and include the IndexError as well!        logging.error("A general error occured,substituting newList with backup")        newList = ["We","can","work","with","this","backup"]        return newList

我遇到的问题是当IndexError被第一个捕获时除外,我的常规错误处理在第二个除了块之外没有应用.

我现在唯一的解决方法是在第一个块中包含一般错误处理代码.即使我将它包装在它自己的功能块中,它仍然看起来不那么优雅……

最佳答案您有两种选择:

>不要使用专用的except块来捕获IndexError.您始终可以通过捕获BaseException并将异常分配给名称(此处为e)来手动测试常规块中的异常类型:

try:    # ...except BaseException as e:    if isinstance(e,IndexError):        logging.error("IndexError occured with newList containing: \n%s",str(newList))    logging.error("A general error occured,substituting newList with backup")    newList = ["We","backup"]    return newList

>使用嵌套的try..except语句并重新引发:

try:    try:        # ...    except IndexError:        logging.error("IndexError occured with newList containing: \n%s",str(newList))        raiseexcept:    logging.error("A general error occured,"backup"]    return newList
总结

以上是内存溢出为你收集整理的Python:通过具有多个Excepts的Try / Except块传播异常全部内容,希望文章能够帮你解决Python:通过具有多个Excepts的Try / Except块传播异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1206220.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存