A practical case of an error class in Python

Many beginners of the Python computer programming language have a difficulty in understanding custom error classes; especially when they want to make use of them in their projects.

I am writing this article with the main purpose of giving a practical example of an error class which I am making use of in a personal project.

Before going any further with this blog post, make sure to launch a new Python interactive shell in your own operating system so you can practice the code being shared in here.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Once you have managed to do that, declare an error class with the help of the Python code which is shown below.

class FFMpegError(Exception):

Then throw the above error by running the code which is being shown below.

raise FFMpegError()

Once the above piece of Python code is executed, the following output should come in your interactive console.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>

The above traceback gives us the __main__.FFMpegException class.

Let’s code the error class which I am using in my personal project.

The practical error class of my ffmpeg wrapper

The error class which I am making use in my real word project is being raised when a file already exists.

Open a new script and create a python module like shown below.


Then create a custom class called FFMpegAlreadyExistsError like shown below.

class FFMpegAlreadyExistsError(Exception):

It is a good practice to define both __str__ and __repr__ magical methods when creating an error class.

class FFMpegALreadyExistsError(Exception):
    def __repr__(self):

    def __str__(self):

Then customize each one of the magic methods defined above with the help of the code which is being shown below.

class FFMpegALreadyExistsError(Exception):
    def __repr__(self):
        return 'File %s already exists' % self.message

    def __str__(self):
        return self.__repr__()

Now that we have finished coding our custom error class, let’s try to raise it like shown below.

raise FFMpegAlreadyExistsError('test.mp4')

Once the above code got executed in my interactive Python console, I got the following output.

File 'test.mp4 already exists'

Final thoughts

The error class which I shared in this article is useful when processing video files that already exist in the current working directory. I am utilizing the code shared in this blog post, in the ffmpeg wrapper which I am coding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *