【问题标题】:Creating Function to handle exceptions in Python在 Python 中创建处理异常的函数
【发布时间】:2018-12-02 20:10:15
【问题描述】:

我想知道是否可以编写一个函数来避免每次在 Python 中为有风险的函数调用 try ... except 块。

我尝试了以下代码,但没有成功:

def e(methodtoRun):
    try:
        methodtoRun.call()
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # __str__ allows args to be printed directly,


def divider(a, b):
    return a / b

e(divider(1,0))

在此代码中,Python 运行 divider(1,0) 并尝试将结果作为参数传递给 e 函数。

我想要做的是传递一个函数作为参数并在函数try ... except块中运行它,这样,如果发生任何错误,我会直接将错误添加到日志中。

这可能吗?

【问题讨论】:

  • 绝对不要这样做。每当引发异常时,您都应该处理它,否则您的程序将无法继续。如果你不能处理它,那么它就是一个不可纠正的异常,你唯一能做的就是让异常冒泡并希望调用者能够处理它。与其尝试创建自己的记录器,不如使用来自the standard library 的记录器。
  • 嗨,正如我在下面的评论中添加的那样,我只需要在日志记录足够的情况下使用它,不需要其他操作。但是对于我需要处理异常的其他情况,我肯定需要单独的异常处理来处理独立的情况。感谢您的评论。

标签: python python-3.x exception-handling


【解决方案1】:

您可以这样做.. 但它确实使代码不是真的更好阅读。

您的示例不起作用,因为您将函数调用divider(1,0) 的“结果”提供给e。它永远不会处理异常,因为您已经调用了函数并且异常已经发生。

您需要将函数本身和任何参数传递给e

改成:

def e(methodtoRun, *args):
    try:
        methodtoRun(*args)    # pass arguments along
    except Exception as inst:
        print(type(inst))    # the exception instance
        print(inst.args)     # arguments stored in .args
        print(inst)          # __str__ allows args to be printed directly,


def divider(a, b):
    return a / b

e(divider,1,0)    # give it the function and any params it needs

获得:

<type 'exceptions.ZeroDivisionError'>
('integer division or modulo by zero',)
integer division or modulo by zero

在任何严肃的代码审查中,您都应该返回您的代码来解决这个问题。我强烈建议不要这样做——你只是在捕获最普遍的异常,而使这个构造更灵活会使其使用起来很糟糕!

例外应该是:

  • 尽可能在本地处理
  • 尽可能具体

您的代码正好相反。

独库:

【讨论】:

  • 嗨,非常感谢,我同意独立处理每个问题的异常,但我需要的是我只需要写到 debug.log 的异常,不需要任何其他具体行动。唯一重要的是认为它不应该破坏程序并让我知道发生了一些事情
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-16
  • 2023-03-07
  • 1970-01-01
相关资源
最近更新 更多