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 - The except ZeroDivisionError block catches the exception and displays a user-friendly message instead of stopping the program. Custom exceptions allow you to define application-specific errors that are not covered by Python's built-in exceptions.
Discussions

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
python - What is considered best practice for custom exception classes? - Software Engineering Stack Exchange
Python has many strong conventions but I'm unclear on how best to manage exceptions for my module. I know it's generally good practice to define a custom exception for your module. E.g.: class MyE... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 18, 2016
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
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
Exceptions come in different types, and the type is printed as part of the message: the types in the example are ZeroDivisionError, NameError and TypeError. The string printed as the exception type is the name of the built-in exception that occurred.
🌐
OneUptime
oneuptime.com › home › blog › how to create custom exceptions in python
How to Create Custom Exceptions in Python
January 22, 2026 - # Base exception for your application class AppError(Exception): """Base exception for the application.""" pass # Category-level exceptions class DatabaseError(AppError): """Database-related errors.""" pass class ValidationError(AppError): """Validation errors.""" pass class AuthenticationError(AppError): """Authentication errors.""" pass # Specific exceptions class ConnectionError(DatabaseError): """Database connection failed.""" pass class QueryError(DatabaseError): """Database query failed.""" pass class InvalidFieldError(ValidationError): """Invalid field value.""" pass class MissingFieldError(ValidationError): """Required field is missing.""" pass
🌐
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
🌐
Reddit
reddit.com › r/python › best practices for custom exceptions?
r/Python on Reddit: Best practices for custom exceptions?
February 24, 2020 -

I got into a debate with a coworker today about best practices in regards to custom exceptions. I created a custom exception class for an exception that is not intended to be caught by the application; we want it to trickle all the way up to the user. I made the class just to give more detailed info to the user when it comes up. During code review, my coworker said that standard practice is to only make custom exception classes for cases that will be handled by the application, and any errors we want the user to see should be one of the built-in Python exception types (ValueError, IndexError, etc.). I hadn't heard of this practice before. Is this actually standard practice? Or is making a custom exception that's intended for the user to see reasonable?

Find elsewhere
Top answer
1 of 2
8

If the library is only used by your own code or in your own organization, then YAGNI applies. You should only make only as many exception sub-classes as you need to handle separately. If two different error conditions are handled in the same way (which may include not handling but termination the application!), then you only need a single exception class.

In other words, only create as many subclasses as you actually need.

I don't really like the idea of error codes. It just introduces an additional way to signal errors which is not supported as nicely by the language (as your code example shows). If you actually need to handle the different error codes differently you might as well make separate exception classes.

2 of 2
5

Exception classes should be as specific as error handling might need to be.

Think about using your code: when each error is raised, how would you want to handle it?

  • Errors that must be handled the same way should be the same class.
  • Errors that you don't see a good reason to handle separately can be the same class until you find a reason.
  • Errors that a user might sometimes have good reason to distinguish should be distinct classes.
    • If one error is a special case of a more general error that you have, make the former a subclass of the latter.
    • If they're just different errors, don't have a subclass relationship between them.

PEP-8 recommends the same thing:

Design exception hierarchies based on the distinctions that code catching the exceptions is likely to need, rather than the locations where the exceptions are raised. Aim to answer the question “What went wrong?” programmatically, rather than only stating that “A problem occurred” (see PEP 3151 for an example of this lesson being learned for the builtin exception hierarchy)

Error codes are at best a low-level implementation detail leaking into your abstractions. Python is a language where it's both beneficial and equally easy to just express each error as a distinct type. So error codes are only justified when you are wrapping a third-party library which already has error codes, and you can't just easily provide a good error class hierarchy over the error codes to better represent the semantics of the errors.

🌐
Real Python
realpython.com › python-exceptions
Python Exceptions: An Introduction – Real Python
March 18, 2026 - With the large number of built-in ... mold. Python makes it straightforward to create custom exception types by inheriting from a built-in exception....
🌐
Codesolid
codesolid.com › writing-a-python-custom-exception
Writing a Python Custom Exception — CodeSolid.com 0.1 documentation
The Python documentation advises that custom exceptions should derive from Exception, not BaseException. To give you an idea of why this is so, consider two of the other classes derived from BaseException: SystemExit and KeyboardInterrupt.
🌐
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")
🌐
Medium
medium.com › codex › exploring-custom-exception-handling-in-python-ffc7042a3bf7
Exploring Custom Exception Handling in Python | by Someone | CodeX | Medium
November 14, 2024 - This allows developers to define exceptions that represent specific errors that occur in their programs, rather than relying solely on the pre-existing exceptions that Python provides.
🌐
Honeybadger
honeybadger.io › blog › a-guide-to-exception-handling-in-python
The ultimate guide to Python exception handling - Honeybadger Developer Blog
March 28, 2025 - Handling exceptions in asynchronous ... context of an async task. Python allows software developers to create custom Python exception classes to handle specific types of errors within their applications....
🌐
Reddit
reddit.com › r/learnpython › custom exception handling
r/learnpython on Reddit: Custom exception handling
April 8, 2024 - That sounds like he could have created a custom "exception hook", which is different from creating a custom exception. Basically, the exception hook is called whenever an exception is unhandled (makes it up all the way to the bottom of the call stack). The default exception hook in Python will show the traceback and exception, like
🌐
Profound Academy
profound.academy › python-mid › custom-exceptions-SJLRxLpQdklXMV4Z803w
Custom Exceptions • Intermediate Python
January 20, 2025 - This allows us to give meaningful ... can't handle. Custom exceptions are created by defining a new class that inherits from the built-in Exception class or one of its subclasses....
🌐
Feldroy
daniel.feldroy.com › posts › attaching-custom-exceptions-to-functions-and-classes
Attaching custom exceptions to functions and classes
August 2, 2012 - >>> try: ... this_function('is an example') ... except this_function.DoesNotCompute: ... print('See what attaching custom exceptions to functions can do?') ...
🌐
Aigents
aigents.co › learn › Custom-Exceptions-python
Custom Exceptions python explained – short, clear and quickly!
Custom exceptions in Python are user-defined error types that enhance the clarity and control of error handling in your applications. While Python offers a variety of built-in exceptions, creating custom exceptions allows developers to define ...
🌐
Python
docs.python.org › 3 › library › logging.html
logging — Logging facility for Python
If the module-level attribute raiseExceptions is False, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom ...
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › python › python custom exceptions
Python Custom Exceptions: Create, Raise, Add Message, and Best Practices
June 21, 2026 - If you adapt an example to read real files from disk, use {run=false} on the opening fence when your Run backend disallows file I/O. A custom exception is a class you define—almost always subclassing Exception (directly or indirectly)—so callers ...
🌐
DevTechie
devtechie.com › blog › custom-exceptions-in-python
Custom Exceptions in Python
December 16, 2024 - In Python, you normally build a custom exception by inheriting from “Exception” class or one of its sub-classes such as the “TypeError” class. The Exception serves as the root class for the majority of built-in Python exceptions. You may alternatively inherit from a different exception, ...