Python Custom Error Types
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more
Python Custom Exception Best Practices
about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users python exception class methods Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each python error vs exception other. Join them; it only takes a minute: Sign up Proper way to declare custom exceptions in modern Python? up vote 595 down vote favorite 158 What's the proper way to declare custom exception classes in modern Python?
Python Exception Message
My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception. By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the
Python Define Exception Inside Class
error: a string, maybe also some other arbitrary object relevant to the exception. I was tripped up by the following deprecation warning in Python 2.6.2: >>> class MyError(Exception): ... def __init__(self, message): ... self.message = message ... >>> MyError("foo") _sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6 It seems crazy that BaseException has a special meaning for attributes named message. I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh. I'm also fuzzily aware that Exception has some magic parameter args, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3. Update: two answers have suggested overriding __init__, and __str__/__unicode__/__repr__. That seems like a lot of typing, is it necessary? python exception share|improve this question edited Jun 5 '12 at 20:37 Eitan T 27.9k113978 asked Aug 23 '09 at 21:29 Nelson 6,43532027 2 *args (or *foo, or *whatever, all that matters is that it has the star in front) is for functions that have an indefinite number of positional arguments. So if you have def myfunction(*args), you can call it like myfunction("foo") or myfunction("foo",
you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions. 8.1. Syntax Errors¶ Syntax errors, also python print exception known as parsing errors, are perhaps the most common kind of complaint
Python Exception Stack Trace
you get while you are still learning Python: >>> while True print 'Hello world' File "
output an error when something in it goes wrong. However, sometimes you may need to create custom exceptions that serves your http://www.programiz.com/python-programming/user-defined-exception purpose. In Python, users can define such exceptions by creating a new class. This exception class has to be derived, either directly or indirectly, from Exception class. Most of the built-in http://programmers.stackexchange.com/questions/275631/when-should-i-subclass-an-exception-in-python exceptions are also derived form this class. >>> class CustomError(Exception): ... pass ... >>> raise CustomError Traceback (most recent call last): ... __main__.CustomError >>> raise CustomError("An error occurred") Traceback (most recent call python exception last): ... __main__.CustomError: An error occurred Here, we have created a user-defined exception called CustomError which is derived from the Exception class. This new exception can be raised, like other exceptions, using the raise statement with an optional error message. When we are developing a large Python program, it is a good practice to place all the user-defined exceptions that our program raises python custom error in a separate file. Many standard modules do this. They define their exceptions separately as exceptions.py or errors.py (generally but not always). User-defined exception class can implement everything a normal class can do, but we generally make them simple and concise. Most implementations declare a custom base class and derive others exception classes from this base class. This concept is made clearer in the following example. Example: User-Defined Exception in Python In this example, we will illustrate how user-defined exceptions can be used in a program to raise and catch errors. This program will ask the user to enter a number until they guess a stored number correctly. To help them figure it out, hint is provided whether their guess is greater than or less than the stored number. # define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # our main program # user guesses a number until he/she gets it right # you
tour help Tour Start here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company Business Learn more about hiring developers or posting ads with us Software Engineering Questions Tags Users Badges Unanswered Ask Question _ Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle who care about creating, delivering, and maintaining software responsibly. Join them; it only takes a minute: Sign up Here's how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top When should I subclass an exception in Python? up vote 6 down vote favorite 1 In my code there are about seven places where I raise an exception. All of these exceptions are treated the same: print an error to log file, return software state to default and exit. During code review my senior engineer, whom I value a lot, said I should subclass all of these exceptions. His argument is that in the future we may want to handle the exceptions differently and that will be easier. My argument is that currently it will only clutter our code and, since we don't know whether we will ever handle the exceptions differently, we should leave the code terse and, if and when the time comes, then and only then we should subtype. I would like to hear any argument for each case. python object-oriented-design exceptions share|improve this question edited Mar 8 '15 at 16:26 jonrsharpe 7361612 asked Mar 8 '15 at 15:36 Ezra 1904 2 YAGNI... You don't need it now and you can always add it later without too much difficulty. –Robert Harvey Mar 8 '15 at 15:56 Do you have any examples? Are you just raising Exception, for example, or more specific built-in errors? –jonrsharpe Mar 8 '15 at 17:50 just raising an Exception("specific description") –Ezra Mar 8 '15 at 18:10 @Ezra at the least, you should see if there's a more fitting built-in exception (see docs.python.org/2/library/exceptions.html). –jonrsharpe Mar 8 '15 at 22:35 add a comment| 1 Answer 1 active oldest votes up vote 4 down vote You're right The argument for your side is already mentioned by Robert Harvey: don't