代码之家  ›  专栏  ›  技术社区  ›  GurhanCagin

在Python中创建处理异常的函数

  •  -1
  • GurhanCagin  · 技术社区  · 7 年前

    try ... except 对于Python中的危险函数,每次阻塞一次。

    我尝试了以下代码,但无效:

    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))
    

    divider(1,0) 并尝试将结果作为参数传递给 e 功能。

    尝试除了 块,这样,如果发生任何错误,我将直接将错误添加到日志中。

    这可能吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Patrick Artner    7 年前

    你可以这样做。。但这并不能让代码更好地阅读。

    您的示例不起作用,因为您提供了函数调用的“结果” 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
    

    但是,在任何认真的代码审查中,您都应该让您的代码返回以修复此问题。我强烈建议不要这样做-您只捕获了最常见的异常,而使此构造更灵活将使其难以使用!

    • 尽可能就地处理
    • 尽可能具体

    您的代码正在执行与之完全相反的操作。

    Doku: