Python exception handling

Python includes a bunch of built-in exception classes and we can easily create our own by creating a class which derives from Exception.

For example, here’s a MethodNotImplementedException type

class MethodNotImplementedException(Exception):
    def __init__(self, *args, **kwargs):
        pass

    def __str__(self):
        return "Method not implemented"

In this example I’ve overridden the __str__ method to return a simple string when we print the exception to stdout.

We need not create specific exception types but obviously this allows us to also catch specific exception types.

Here’s an example of some code that raises (throws) an exception and the code to catch and handle an exception

class Animal:
    def name(self):
        raise MethodNotImplementedException()


a = Animal()
try:
    a.name()
except MethodNotImplementedException as e:
    print(e)
except Exception as e:
    raise
finally:
    print("finally called")

We create a try block and exceptions are caught using the except statement. As can be seen we can catch and filter each exception type we want to handle and include a finally block as required.

To rethrow and exception we simple call the raise method.