python - 重复尝试和排除子句

标签 python try-catch except

我创建了一堆函数,我需要在所有函数中使用非常相似的 except 子句,但我讨厌在每个函数中有这么多行的 try 和 except 子句以及相同的代码。例如:

import sys
import random

def foo():
    num=random.random()
    try:
        if num>0.5: print 'OK'
        elif num>0.25: raise NameError('Too Small')
        else: raise KeyboardInterrupt
    except NameError:
        print "%s had a NameError" % sys._getframe().f_code.co_name
    except:
        print "%s had a different Error" % sys._getframe().f_code.co_name

def bar():
    num=random.random()
    try:
        if num>0.8: print 'OK'
        elif num>0.6: raise NameError('Too Small')
        else: raise KeyboardInterrupt
    except NameError:
        print "%s had a NameError" % sys._getframe().f_code.co_name
    except:
        print "%s had a different Error" % sys._getframe().f_code.co_name

“try”后面的代码对于函数是不同的,但是“except”后面的代码是一样的。我想合并那些 except 语句,这样它们就不会让我的代码看起来那么局促。有什么好的方法吗?

最佳答案

Python Decorators是你想要的。

你说过 except block 总是相同的。制作一个自定义装饰器来做你想做的事。您必须将它应用于每个函数/方法,但它确实可以避免重复。

def handleError(function):
    def handleProblems():
        try:
            function()
        except Exception:
            print "Oh noes"
    return handleProblems


@handleError
def example():
   raise Exception("Boom!")

当调用一个应用了装饰器的方法时:

>>> 
>>> example()
Oh noes
>>> 

您将需要更改异常类型以及您所做的事情,但您应该明白我要做什么。

关于python - 重复尝试和排除子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9386592/

相关文章:

python - 在 Python 中替换一个大字符串中的多个字符串的推荐方法是什么?

java - 用于扫描的简单 try & catch 代码不适用于十进制值

javascript - 使用 node.js 创建缓冲区期间捕获错误

java - 使用现有的 try/catch block 或重复的 catch block 而不引发异常

python - OOP/try except 类的 __init__ 中的语句

c# - 使用 Linq 除了不像我想的那样工作

python - 类似于 Python 中的 Pojo 类

python - sympy:向量/矩阵重复

python - 使用正则表达式将python中的大写重复字母替换为单个小写字母

python - 简单的Python Q : idk what produces None when this code's executed