Handling a File Error

As already pointed out in the exceptions lesson, Python contains a vast set of built-in exceptions. One important class has to do with file handling. The example presented in the lesson will help to review file handling methods and put them in the context of handling exceptions.

Best Practices for Custom Exceptions

When you are developing a package, it is very handy to define exceptions that are exclusive to it. This makes it much easier to handle different behaviors and gives developers a very efficient way to filter whether the problems are within your package or with something else. Imagine, for instance, that you are working with a complex package, and you want to write to a file every time an exception from that specific package appears.

This is very easy to achieve if all the exceptions inherit from the same base class. The code below is a bit longer, but it is built on top of all the examples above, so it should be easy to follow:

class MyException(BaseException):
    pass

class NonPositiveIntegerError(MyException):
    pass

class TooBigIntegerError(MyException):
    pass

def average(x, y):
    if x<=0 or y<=0:
        raise NonPositiveIntegerError('Either x or y is not positive')

    if x>10 or y>10:
        raise TooBigIntegerError('Either x or y is too large')
    return (x+y)/2

try:
    average(1, -1)
except MyException as e:
    print(e)

try:
    average(11, 1)
except MyException as e:
    print(e)

try:
    average('a', 'b')
except MyException as e:
    print(e)

print('Done')
We first define an exception called MyException, which is going to be our base exception. We then define two errors,  NonPositiveIntegerError and TooBigIntegerError  which inherit from  MyException. We define the function average  again but this time we raise two different exceptions. If one of the numbers is negative or larger than 10.

When you see the different use cases below, you will notice that in the try/except  block, we are always catching MyException, but not one of the specific errors. In the first two examples, when passing  -1 and 11 as arguments, we successfully print to screen the error message, and the program keeps running. However, when we try to calculate the average between two letters, the  Exception is going to be of a different nature, and is not going to be caught by the Except . You should see the following on your screen:

TypeError: '<=' not supported between instances of 'str' and 'int'