Maybe I missed the question, but why not:

class MyException(Exception):
    pass

To override something (or pass extra args), do 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

That way you could pass dict of error messages to the second param, and get to it later with e.errors.

In Python 2, you have to use this slightly more complex form of super():

super(ValidationError, self).__init__(message)
Answer from gahooa on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-custom-exceptions-in-python
Define Custom Exceptions in Python - GeeksforGeeks
June 27, 2026 - Explanation: When 10/0 is executed, Python raises a ZeroDivisionError. The except ZeroDivisionError block catches the exception and displays a user-friendly message instead of stopping the program.
🌐
OneUptime
oneuptime.com › home › blog › how to create custom exceptions in python
How to Create Custom Exceptions in Python
January 22, 2026 - The simplest custom exception just inherits from Exception: class ValidationError(Exception): """Raised when data validation fails.""" pass # Usage def validate_email(email): if '@' not in email: raise ValidationError(f"Invalid email: {email}") ...
Discussions

How do I declare custom exceptions in modern Python? - Stack Overflow
There are good points in several ... to customised exceptions is in v3.13. I also feel the other answers mostly address aspects of the approach without a full description of implementation and usage. At the risk of crowding this question I'm putting my current approach (using Python v3.10) with a usage scenario to attempt to collate the most recent advice. This example has ... More on stackoverflow.com
🌐 stackoverflow.com
Custom exception handling
The golden rule with exceptions is to only catch errors you know you can deal with. So if you have a function that you know could fail in a specific way, it's best to create a custom exception for that specific case and raise it inside the function. That way you can catch only that exception, but leave everything else - all the actual unexpected errors - for your general error-handling code. I don't know what you mean by using sys and runtime variables though, an exception class doesn't have to do anything at all: this is a perfectly good one: class MyException(Exception): pass More on reddit.com
🌐 r/learnpython
9
7
April 8, 2024
Best practices for custom exceptions?
Why would a user ever want to see an exception? Are you writing a library and your so-called "user" is actually another programmer? More on reddit.com
🌐 r/Python
4
1
February 24, 2020
Context manager cookbook - 10+ custom examples
I see you've posted a GitHub link to a Jupyter Notebook! GitHub doesn't render large Jupyter Notebooks, so just in case, here is an nbviewer link to the notebook: https://nbviewer.jupyter.org/url/github.com/RadoslawB/learning-machine-learning/blob/master/notebooks/python-api/context-manager-examples.ipynb Want to run the code yourself? Here is a binder link to start your own Jupyter server and try it out! https://mybinder.org/v2/gh/RadoslawB/learning-machine-learning/master?filepath=notebooks%2Fpython-api%2Fcontext-manager-examples.ipynb I am a bot. Feedback | GitHub | Author More on reddit.com
🌐 r/Python
7
313
April 13, 2021
🌐
Readthedocs
pynote.readthedocs.io › en › latest › ExceptionsHandling › CustomExceptions.html
Custom Exceptions in Python — pynotes documentation
In Python, users can define custom exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from the built-in Exception class. Most of the built-in exceptions are also derived from this class. In this example, we will illustrate how user-defined ...
🌐
Programiz
programiz.com › python-programming › user-defined-exception
How to Define Custom Exceptions in Python? (With Examples)
In Python, we can define custom exceptions by creating a new class that is derived from the built-in Exception class.
🌐
Python Tutorial
pythontutorial.net › home › python oop › python custom exception
Python Custom Exception
March 28, 2025 - class CustomException(Exception): """ my custom exception class """Copy · Note that the CustomException class has a docstring that behaves like a statement. Therefore, you don’t need to add the pass statement to make the syntax valid. To raise the CustomException, you use the raise statement. For example, the following uses the raise statement to raise the CustomException:
🌐
CodingNomads
codingnomads.com › python-throw-exception-custom
Python Custom Exceptions
Previously, you raised a ValueError in the case that someone added an age value that was below zero: age = int(input("Age: ")) if age < 0: raise ValueError("Looks like you're not born yet.") That's not bad, but ValueError is a built-in exception, ...
Top answer
1 of 16
2073

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

To override something (or pass extra args), do 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

That way you could pass dict of error messages to the second param, and get to it later with e.errors.

In Python 2, you have to use this slightly more complex form of super():

super(ValidationError, self).__init__(message)
2 of 16
760

With modern Python Exceptions, you don't need to abuse .message, or override .__str__() or .__repr__() or any of it. If all you want is an informative message when your exception is raised, do this:

class MyException(Exception):
    pass

raise MyException("My hovercraft is full of eels")

That will give a traceback ending with MyException: My hovercraft is full of eels.

If you want more flexibility from the exception, you could pass a dictionary as the argument:

raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})

However, to get at those details in an except block is a bit more complicated. The details are stored in the args attribute, which is a list. You would need to do something like this:

try:
    raise MyException({"message":"My hovercraft is full of animals", "animal":"eels"})
except MyException as e:
    details = e.args[0]
    print(details["animal"])

It is still possible to pass in multiple items to the exception and access them via tuple indexes, but this is highly discouraged (and was even intended for deprecation a while back). If you do need more than a single piece of information and the above method is not sufficient for you, then you should subclass Exception as described in the tutorial.

class MyError(Exception):
    def __init__(self, message, animal):
        self.message = message
        self.animal = animal
    def __str__(self):
        return self.message
Find elsewhere
🌐
DevTechie
devtechie.com › blog › custom-exceptions-in-python
Custom Exceptions in Python
December 16, 2024 - For example, if you are a user registration module/API; there may be numerous situations which lead to non-registration of user such as password does not qualify password rules, username is already taken, invalid email address given etc. Here, you can define a base custom exception class which is a sub-class of Python’s Exception class, let’s say this class — RegistrationFailed.
🌐
Medium
martinxpn.medium.com › custom-exceptions-in-python-creating-custom-exceptions-59-100-days-of-python-4f26de8e851d
Custom Exceptions in Python — Creating Custom Exceptions (59/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - For example, if you are creating a banking application, you may want to define an exception that is raised when a user tries to withdraw more money than they have in their account.
🌐
Jacob Padilla
jacobpadilla.com › writing › custom-python-exceptions
Python Custom Exceptions: How to Create and Organize Them
October 27, 2024 - Many times, it can be much better to make tailored exceptions for specific scenarios in your projects. For example, let's say you're building a social media bot that posts tweets on Twitter/X for you.
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to define custom exception classes in python
How to Define Custom Exception Classes in Python | Towards Data Science
March 5, 2025 - This is just a syntax help that Python adds when you raise an exception · In the second example, MyCustomError is passed with a string argument of 'We have a problem'. This is set as the message attribute in the object and printed in the error message when the exception is raised. The code for the MyCustomError exception class can be found here. Let's progress now, and demonstrate how custom ...
🌐
GeeksforGeeks
geeksforgeeks.org › user-defined-exceptions-python-examples
User-defined Exceptions in Python with Examples - GeeksforGeeks
January 4, 2025 - # NetworkError has base RuntimeError and not Exception class Networkerror(RuntimeError): def __init__(self, arg): self.args = arg try: raise Networkerror("Error") except Networkerror as e: print(e.args) ... help() function in Python is a built-in function that provides information about modules, classes, functions and modules. It is useful for retrieving information on various Python objects. Example:Pythonhelp()OutputWelcome to Python 3.13's help utility!
🌐
KDnuggets
kdnuggets.com › how-and-why-to-create-custom-exceptions-in-python
How (and Why) To Create Custom Exceptions in Python - KDnuggets
You can create a custom exception in Python by subclassing the built-in Exception class. class MyCustomError(Exception): """Custom exception for a specific error""" pass · Now, let's implement custom exceptions for an example inventory management ...
🌐
Better Stack
betterstack.com › community › questions › how-to-declare-custom-exceptions-in-python
Proper way to declare custom exceptions in modern Python? | Better Stack Community
March 2, 2023 - To manually raise an exception in Python, use the raise statement. Here is an example of how to use it: def calculate_payment(amount, payment_type): if payment_type != "Visa" and payment_type ...
🌐
YouTube
youtube.com › watch
How To Create Custom Exceptions In Python - YouTube
In this video I will be showing you how you can easily create your own custom exceptions in Python easily.▶ Become job-ready with Python:https://www.indently...
Published: October 29, 2024
🌐
LinkedIn
linkedin.com › pulse › custom-exceptions-learn-how-create-your-handle-errors-h-s-karthik
Custom Exceptions: Learn how to create your custom exceptions to handle application-specific errors gracefully.
September 17, 2023 - In this article, I will walk you through the process of creating custom exceptions in Python, a versatile and widely-used programming language. I'll provide you with code examples to illustrate how to define, raise, and handle custom exceptions effectively.
🌐
Luis Llamas
luisllamas.es › home › courses › python programming course
Custom Exceptions in Python
December 7, 2024 - class ConnectionError(Exception): def __init__(self, message): super().__init__(message) class TimeoutError(ConnectionError): def __init__(self, time): self.time = time super().__init__(f"Timeout exceeded: {time} seconds") ... Once custom exceptions ...
🌐
Learn Python
learnpython.dev › 03-intermediate-python › 40-exceptions › 90-custom-exceptions
Custom Exceptions :: Learn Python by Nina Zakharenko
", line 1, in __main__.MyCustomException It’s OK to have a custom Exception subclass that only pass-es - your exception doesn’t need to do anything fancy to be useful.
🌐
PythonHello
pythonhello.com › problems › exceptions › how-to-create-custom-exceptions
How to create custom exceptions in Python
You can also define custom exception classes that inherit from more specific built-in exception classes. For example, if you wanted to create a custom exception for input validation errors, you could define a class that inherits from the built-in ValueError class:
🌐
MakeUseOf
makeuseof.com › home › programming › how to create custom exceptions in python
How to Create Custom Exceptions in Python
September 19, 2023 - When the custom exception occurs, it includes the original exception as a __cause__ attribute, providing a link between the custom exception and the original. This lets you trace the origin of an exception. By wrapping exceptions, you can provide more meaningful context and send more appropriate error messages to users, without revealing internal implementation details of your code or the API. It also lets you manage and address types of errors in a structured and uniform way. By inheriting the base exception class that Python provides, you can create simple and useful exceptions that you can raise when specific errors occur in your code.