0

我一直在玩弄使用错误处理。特别是用户定义的错误。python可重用用户错误处理

但是我不确定如果下面的方法不好的想法/推荐/简单的奇怪?

import operator 
from functools import partial 


class GenericError(Exception): 
    def __init__(self, value): 
     self.value = value 
    def __str__(self): 
     return repr(self.value) 


def errorhandle(error, func): 
    print(func.__name__, "says: ", error) 
# or perhaps error_dictionary[error] 


def f_test_bool(x, bo, y, et, m, ef): 
    """ generic boolean test. If boolean_operator(x,y) == True --> raise passed in Error """ 
    try: 
     if bo(x,y): 
      raise et(m) 
     else: 
      return x 
    except et as err: 
     ef(err, f_test_bool) 



partial_ne = partial(f_test_bool, 
        bo=operator.__ne__, 
        et=GenericError, 
        ef=errorhandle) 

partial_ne(x = 5, 
      y = 6, 
      m = "oops, 5 is not equal to 6") 




>>> imp.reload(errorhandling) 
f_test_bool says: 'oops, 5 is not eqal to 6' 

我的想法是这样,我可以有一个简单的模块,我可以重新使用,并且管的值通过,而无需用户定义的错误添加到我写的任何新功能。我认为这会让事情更清洁。

回答

1

对于那些应该简单明了的东西,你会增加很多开销。不要忘了zen

简单胜于复杂。

为什么不干脆:

if 5 != 6: 
    raise ValueError('oops, 5 is not equal to 6') 
+0

我在想,这样我可以通过函数的返回值,分别控制错误,而不是过多的尝试结束了:除了块。提出的错误可能是退出程序,或仅仅是提到发生了什么。 – beoliver 2012-07-11 20:59:08

+0

错误应该总是例外,所以我看不到他们可能传输的返回值。如果您只想记录某些内容,请使用['logging'](http://docs.python.org/library/logging.html)模块。 – phihag 2012-07-11 21:04:53

+0

我的意思是说,如果没有错误,返回值(测试过的),当它失败时,错误被传递给'errorhandle'函数,然后它可能包含一个用于处理特定错误的字典。 – beoliver 2012-07-11 21:11:35