quantifiedcode / python-anti-patterns

An open collection of Python anti-patterns and worst practices.
https://quantifiedcode.github.io/python-anti-patterns
Other
1.71k stars 249 forks source link

Misuse of Exception in example #45

Closed Brobin closed 9 years ago

Brobin commented 9 years ago

In no_exception_type_specified.rst, we are presented with this example.

class DivisorTooSmallError(StandardError):
    def __init__(self, arg):
        self.args = arg

def divide(a, b):
    result = None
    try:
        # Raise an error if b is < 1
        if b < 1:
            raise DivisorTooSmallError
        result = a / b
    except DivisorToSmall:
        # b is below 1
        print "DivisorToSmall error: set result = 1"
        result = 1

    return result

I think this is an abuse of exception handling. The purpose of raising exceptions is to notify the caller of the function that execution of the program cannot be continued.

In this case, the exception is thrown and caught in the same method, which I think in itself is an anti-pattern, because the caller is itself. Also, if b is less than 0, or is 0, we should be throwing more specific excpetions, not setting the result to 1!

10 / 0 != 1 10 / 0 == undefined, throw an exception

I think that a better example of using exceptions effectively wihtout introducing more anti-patterns would be like the following

class DivisorTooSmallError(StandardError):
    def __init__(self, arg):
        self.args = arg

def divide(a, b):
    if b < 1:
        raise DivisorTooSmallError
    return a / b

try:
    divide(10, 0)
except DivisorTooSmallError:
    print("Unable to divide these numbers!)

In this case the exception is handled by the caller (like it should be), not in the same method that it was thrown.

vogelsgesang commented 9 years ago

First of all sorry that you had to wait such a long time for a reply.

I agree, the example is misleading and should be changed. Your example is much better and I would love it to have your example in this document instead of the current one.

So, do you want to make a pull request in order to appear in the git log? Or should I just copy your example over?

Brobin commented 9 years ago

I can get a pull request up this weekend. Thanks!

vogelsgesang commented 9 years ago

Thanks :) Just ping me in the pull request and I will make sure it gets merged as fast as possible.