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
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
🌐
GeeksforGeeks
geeksforgeeks.org › python › define-custom-exceptions-in-python
Define Custom Exceptions in Python - GeeksforGeeks
June 27, 2026 - To create a custom exception, define a class that inherits from Python's built-in Exception class. ... class MyCustomError(Exception): """Exception raised for custom error scenarios.""" def __init__(self, message): self.message = message ...
Discussions

raising Custom Exception
You’ll have to override its __repr_ method. But it’s really meant for debugging, not as part of the “nice” output of a finished program. The module name gives you information about where the exception was defined, but like the rest of the stack trace you likely see it in, it’s meant for a programmer, not the end user. More on reddit.com
🌐 r/learnpython
11
1
April 16, 2025
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
I am trying to learn how to raise Custom Errors in Python. I want to write a program which doesn't raise Custom Error when the value is any integer or "quit" but when I enter string other than "quit" it does raise Custom Error.(Beginner)
Try putting parenthesis around the int(a) > 6 and int(a) < 9. You could also shorten it like: if a == “quit” or not (6 < int(a) < 9) I’m not sure if you still need the parenthesis in this case. You might not More on reddit.com
🌐 r/learnpython
16
2
December 23, 2024
Help with making custom exception?
You need to subclass an existing exception class . If you're not sure which one, just subclass Exception like you did in EmptyWalletValue. FYI, it's probably best to always name your exceptions so that they end with Error to make it very clear what the class is. More on reddit.com
🌐 r/learnpython
5
1
June 10, 2022
🌐
Medium
medium.com › @jyotijingar › understanding-raise-assert-and-custom-exceptions-in-python-ac67775e23d6
Understanding raise, assert, and Custom Exceptions in Python | by jyoti jingar | Medium
August 23, 2025 - The raise keyword is used to manually trigger exceptions. You can raise either built-in exceptions or your own custom exceptions.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define __str__() to print all the arguments without explicitly accessing .args. >>> try: ... raise Exception('spam', 'eggs') ...
🌐
Real Python
realpython.com › python-raise-exception
Python's raise: Effectively Raising Exceptions in Your Code – Real Python
October 20, 2025 - In Python, you can raise two different kinds of exceptions: Built-in exceptions: These exceptions are built into Python. You can use them directly in your code without importing anything. User-defined exceptions: Custom exceptions are those that you create when no built-in exception fits your needs.
🌐
CodingNomads
codingnomads.com › python-throw-exception-custom
Python Custom Exceptions
class MyCustomError(Exception): pass try: raise MyCustomError except MyCustomError: print("Oh, emptiness!") Custom exceptions that don't do more than define a new name are quite common in Python.
🌐
DevTechie
devtechie.com › blog › custom-exceptions-in-python
Custom Exceptions in Python
December 16, 2024 - Max marks is 100") else: print ... (such as an error message or other relevant data), you can add your own attributes to the custom exception class and override the constructor (__init__()) method....
Find elsewhere
🌐
OneUptime
oneuptime.com › home › blog › how to create custom exceptions in python
How to Create Custom Exceptions in Python
January 22, 2026 - While Python's built-in exceptions cover many cases, custom exceptions let you communicate domain-specific errors clearly. They make error handling more precise and your codebase more maintainable. 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}") return True try: validate_email("invalid-email") except ValidationError as e: print(f"Validation failed: {e}")
🌐
Reddit
reddit.com › r/learnpython › raising custom exception
r/learnpython on Reddit: raising Custom Exception
April 16, 2025 -

[SOLVED] adding __module__ = "builtin" to the exception class works, thanks to everyone who tried to to help

I created a custom Exception which works as expected, however I don't call this class from within the same file but have it in a seperate errors.py file to keep things organized. Now when I raise the exception it not only shows the exception's name but also the file it is in at the beginning of the error message. Is there a way I can avoid this?

Message I have now: "errors.MyException: Error Message"
Message I want: "MyException: Error Message"

EDIT: I raise the exception like this:

from errors import MyException

raise MyException("Error Message")
🌐
Python Tutorial
pythontutorial.net › home › python oop › python custom exception
Python Custom Exception
March 28, 2025 - class CustomException(Exception): ... the pass statement to make the syntax valid. To raise the CustomException, you use the raise statement....
🌐
MakeUseOf
makeuseof.com › home › programming › how to create custom exceptions in python
How to Create Custom Exceptions in Python
September 19, 2023 - It uses the super() method to call ... handling. To raise an error, use the raise keyword followed by an instance of your custom exception class, passing it an error message as an argument:...
🌐
Readthedocs
pynote.readthedocs.io › en › latest › ExceptionsHandling › CustomExceptions.html
Custom Exceptions in Python — pynotes documentation
Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self, salary, message="Salary is not in (5000, 15000) range"): self.salary = salary self.message = message super().__init__(self.message) salary = int(input("Enter salary amount: ")) if not 5000 < salary < 15000: raise SalaryNotInRangeError(salary) ... Here, we have overridden the constructor of the Exception class to accept our own custom arguments salary and message.
🌐
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 - If the user enters a list or tuple for the keys and values, the two iterables will be zipped together using the python zip function. The zipped variable which points to the zip object can be iterated over, and the tuples can be unpacked. As we iterate through the tuples, I check to see whether the val is an instance of the int or float class. If it is not, I raise a custom IntFloatValueError with val passed as an argument. When we raise a IntFloatValueError exception, we are creating an instance of the IntFloatValueError class and printing it at the same time.
🌐
KDnuggets
kdnuggets.com › how-and-why-to-create-custom-exceptions-in-python
How (and Why) To Create Custom Exceptions in Python - KDnuggets
We'll define three custom exceptions to handle these cases: OutOfStockError: Raised when a product is out of stock; when its count drops to zero.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python custom exceptions
Python Custom Exceptions: Create, Raise, Add Message, and Best Practices
June 21, 2026 - Learn how to create custom exceptions in Python by subclassing Exception, raise custom exceptions with messages, catch them, add attributes, chain exceptions, and follow best practices.
🌐
GeeksforGeeks
geeksforgeeks.org › python › user-defined-exceptions-python-examples
User-defined Exceptions in Python with Examples - GeeksforGeeks
Example: This example shows how to create a custom exception NetworkError by inheriting from RuntimeError, which is a standard built-in exception. ... # NetworkError has base RuntimeError and not Exception class NetworkError(RuntimeError): def __init__(self, arg): self.args = (arg,) # store as tuple try: raise NetworkError("Connection failed") except NetworkError as e: print(e.args)
Published: February 12, 2026
🌐
Programiz
programiz.com › python-programming › user-defined-exception
How to Define Custom Exceptions in Python? (With Examples)
Enter salary amount: 2000 Traceback (most recent call last): File "<string>", line 17, in <module> raise SalaryNotInRangeError(salary) __main__.SalaryNotInRangeError: Salary is not in (5000, 15000) range · Here, we have overridden the constructor of the Exception class to accept our own custom arguments salary and message.
🌐
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 - The __init__ method allows us to provide an error message when the exception is raised. To raise your custom exception, you can use the raise keyword followed by an instance of your custom exception class.
🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - ... There are scenarios where you might want to stop your program by raising an exception if a condition occurs. You can do this with the raise keyword: You can even complement the statement with a custom ...