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 OverflowMaybe 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)
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
Best practices for custom exceptions?
python - What is considered best practice for custom exception classes? - Software Engineering Stack Exchange
raising Custom Exception
Custom exception handling
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?
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.
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.
[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")