DEV Community

Cover image for Custom Exceptions in Python
bluepaperbirds
bluepaperbirds

Posted on

1

Custom Exceptions in Python

Python Applications may call custom exceptions by creating a brand new exception class. Custom Exceptions need to be derived from the Exception class.

What is an Exception?

An exception can be thrown with the raise keyword. They can be handled with the try-catch block.

You can try this in the Python shell, by typing raise Exception("your message").

➜  ~ python3
Python 3.7.5 (default, Nov 20 2019, 09:21:52) 
[GCC 9.2.1 20191008] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> raise Exception("No can do")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: No can do
>>> 

All built-in exceptions use the Exception class. User-defined exceptions should be derived from this class (inherited).

Custom Exception

The program shown below creates a custom exception HappyError that inherits from the Exception class.

class HappyError(Exception):
    pass

raise HappyError("To happy to run")

The above program then raises the HappyError exception:

➜  ~ python3 program.py
Traceback (most recent call last):
  File "t.py", line 5, in <module>
    raise HappyError("To happy to run")
__main__.HappyError: To happy to run

Many modules define their own exceptions.

Optionally you can override the constructor like this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors

But with Python 3 Exceptions, you don't need to do override anything. If all you want is an informative message for your exception, do this:

class MyException(Exception):
    pass

raise MyException("My car is swimming")

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

Top comments (1)

Collapse
 
waylonwalker profile image
Waylon Walker β€’

Custom exceptions make exceptions so much clearer.

Neon image

Set up a Neon project in seconds and connect from a Python application

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay