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
Python exception handling: Understanding raise statement
In comparison to try, except, else, and finally blocks, raise statement seems not always needed. Consider that all of these exceptions you're getting in your code have to come from somewhere - and that you, a programmer eventually writing Python code that other people will use, may desire to implement your own system of exceptions so that the programmers using your code can respond to exceptional situations when they occur. Didn't you wonder how that works? How you create an exception, rather than just handling one that comes from somewhere else? More on reddit.com
🌐 r/learnpython
4
3
September 4, 2024
Should a custom Exception also log its message in init if I'm doing both while raising anyway?
i feel like this can get nutty really fast. and not in a good way. any reasons to write it like this? More on reddit.com
🌐 r/learnpython
4
2
February 3, 2024
Defining CUstom Exception Classes in Python
I don't want to sound too negative, but I can't really recommend this. There's almost never a case for catching a base Exception, you should catch only those you expect, i.e ValueError, NameError You should also catch the exceptions by type - the except clause accepts either a class or a tuple of classes and matches on type. I don't think I've ever seen a use case where defining a new Exception was necessary or advisable; Python provides enough to suit almost every case. Custom exceptions cause noise in your code, also you need to read the implementation to figure out when it's raised, what the intention is etc. Coding by convention is a powerful thing, people know roughly what's gone wrong if an AttributeError pops up, not so much if it's a CustomServiceInjectionAttributeNotDefinedError. EDIT: 4. You named your custom classes MyNameError, but you inherit from Exception - not a good idea, because your MyNameError is now not a NameError at all! More on reddit.com
🌐 r/pythontips
10
10
January 23, 2021
🌐
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.
🌐
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.
🌐
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.
Find elsewhere
🌐
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....
🌐
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")
🌐
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....
🌐
Learn Python
learnpython.dev › 03-intermediate-python › 40-exceptions › 90-custom-exceptions
Custom Exceptions :: Learn Python by Nina Zakharenko
This makes it super easy to create our own custom exceptions, which can make our programs easier to follow and more readable. An exception need not be complicated, just inherit from Exception: >>> class MyCustomException(Exception): ... pass ... >>> raise MyCustomException() Traceback (most recent call last): File "<stdin>", line 1, in <module> __main__.MyCustomException
🌐
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}")
🌐
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 ...
🌐
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:...
🌐
AskPython
askpython.com › python › python-custom-exceptions
Python Custom Exceptions - AskPython
August 6, 2022 - We are in complete control of what this Exception can do, and when it can be raised, using the raise keyword. Let us look at how we can define and implement some custom Exceptions.
🌐
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
🌐
Codesolid
codesolid.com › writing-a-python-custom-exception
Writing a Python Custom Exception — CodeSolid.com 0.1 documentation
We’ve written a custom exception in two lines of code, and the second line was just to let Python know that we finished declaring our RanOutOfSomething exception class. By the way, an alternative syntax is to use a docstring here: class RanOutOfSomething(Exception): """The cupboard is bare.""" Either way, the real work is done on the first line. We declare a class as a child of Python’s built-in Exception, and we’re done. Raising (throwing) such an exception is even easier than creating them.
🌐
PythonHello
pythonhello.com › problems › exceptions › how-to-create-custom-exceptions
How to create custom exceptions in Python
To create a custom exception in Python, you need to create a new class that inherits from the Exception class. This class should have a init method that takes in any necessary arguments and sets them as attributes of the exception.
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python custom exceptions
Python Custom Exceptions: Create, Raise, Add Message, and Best Practices
June 21, 2026 - Treating a path as a directory when a file already exists at the same path, which raises FileExistsError for mkdir. Define custom exceptions as Exception subclasses, raise them when domain rules fail, and catch them by type.