Monday 1 September 2014

Catching too general exception :: Pylint :: W0703


Error:

Catching too general exception

Description

Raised by Pylint, when an except clause doesn't specify exceptions type to catch and use general Exception. This error is not fatal but considered a bad practice, good practice require to catch specific exception like ZeroDivisionError.

Example(s)

Given sample of code describe basic divide function, it takes two arguments a and b. We have simple divided first argument with second and returned result. Although their exist potential exception like ZeroDivisionError, we have used general exception to catch errors.

def divide(a, b):
    """
    function to take two arguments to divide first by second
    """
    try:
        result = a/b
    except Exception as ex:
        result = 0
    return result

Solution(s)

Good programming practice is to catch very specific range of types. Using general Exception without specifying type of exception will result in catching not just the errors you planned for, but other errors too, this may mask bugs in your code that would be quicker to diagnose if they weren't caught at all, or possibly would be better dealt with by a single very high level exception handler.

Use  Specific Exceptions
Use more specific exceptions like  ZeroDivisionError, TypeError.

def divide(a, b):
    """
    function to take two arguments to divide first by second
    """
    try:
        result = a/b
    except ZeroDivisionError:
        result = 0
    except TypeError:
        result = 0
    return result

No comments:

Post a Comment