简体   繁体   中英

Create custom exception or use existing

I have a function:

def f(x):

    if x == 'dog':
        print('ok')
    elif x == 'cat':
        print('ok')
    else:
        raise MyException('Not an x i would expect')

I m adding an exception in case one day i change whatever supplies x to f() and forget to fix f() , so that i can easily find the problem.

  1. Is this the wrong way to "remember" to change f() when needed?

Secondly, f() is a part of another function that might get a decorator that handles certain exceptions:

@an_exception_handler
def g(x):
    f(x)
    return 1000 

I don't want @an_exception_handler to accidentally handle MyException (if MyException is child of ValueError for example, and @an_exception_handler handles ValueError ).

  1. Should MyException be a custom exception, or use an existing rarely occurring exception?

If you really don't want to make MyException a subclass of ValueError you should definitely make your own exception class, except you find another exception class that describes the exception equally good.

To be honest, your way of handling "all ValueError s but this one" (and by concept this definitely is a ValueError ) feels a bit inconsidtent. What are you trying to accomplish with that?

As PM 2Ring pointed out in his comment, an assertion would also be a good way to go. Probably better than another exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM