0

I have been playing around with using error handling. In particular with user defined errors.

However I am not sure if the following approach a bad idea / recommended / plain weird?

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'

my thought was that this way, I could have a simple module that I can re-use, and pipe values through without having to add user-defined errors to any new functions that I write. I thought this would keep things cleaner.

beoliver
  • 5,579
  • 5
  • 36
  • 72

1 Answers1

1

You're adding a lot of overhead for something that should be simple and obvious. Don't forget the zen:

Simple is better than complex.

Why not simply:

if 5 != 6:
   raise ValueError('oops, 5 is not equal to 6')
phihag
  • 278,196
  • 72
  • 453
  • 469
  • I was thinking that this way I can pass the return values of functions through, control the errors separately and not end up with excessive try: except blocks. The raised Errors may be to exit the program, or merely to mention what occurred. – beoliver Jul 11 '12 at 20:59
  • Errors should always be exceptional, so I don't see what return value they could possibly transport. If you just want to log something, use, well, the [`logging`](http://docs.python.org/library/logging.html) module. – phihag Jul 11 '12 at 21:04
  • I mean that if there is not an error, the value (that was tested) is returned, and when it fails, the error is passed to the `errorhandle` function, which would then contain perhaps a dictionary for dealing with specific errors. – beoliver Jul 11 '12 at 21:11
  • How often do you expect to need this specific construct? Also, how could a generic function ever deal with the errors? The correct error handler is either the local code (i.e. ignore the error, or somehow get better values, or disable a feature), or someone in the callstack (i.e. abort large action, show error message, ignore error) – phihag Jul 11 '12 at 21:15
  • probably not as often as the overhead lends itself to! I just thought it was interesting and was wondering if it is ever advantageous to use this approach. – beoliver Jul 11 '12 at 21:23