Python Raise Error In Constructor
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 about hiring developers or posting ads with python __init__ try except us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow
Python Exception __init__
Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up python exception class Python: is it bad form to raise exceptions within __init__? up vote 59 down vote favorite 10 Is it considered bad form to raise exceptions within __init_? If so, then what is the accepted method of throwing an error when certain class
Python 3 Exceptions
variables are initialized as None or of an incorrect type? python exception share|improve this question asked Oct 1 '09 at 23:47 meppum 80331114 In C, it's bad form to raise an exception in the destructor, but constructor should be fine. –Calyth Oct 2 '09 at 0:17 3 @Calyth, you mean C++ -- there are no constructors or destructors in C. –Alex Martelli Oct 2 '09 at 14:55 2 ...or exceptions, for that matter. –Matt Wilding Sep 19 '13 at 20:04 python valueerror example @Calyth: lol, please remove that nonsensical statement made by an innocent typo ;-) –lpapp Sep 8 '14 at 15:58 2 @lpapp yes. C++. FML. And I couldn't edit that comment. So the internet shall document my idiocy ;) –Calyth Sep 23 '14 at 21:35 add a comment| 7 Answers 7 active oldest votes up vote 83 down vote accepted Raising exceptions within __init__() is absolutely fine. There's no other good way to indicate an error condition within a constructor, and there are many hundreds of examples in the standard library where building an object can raise an exception. The error class to raise, of course, is up to you. ValueError is best if the constructor was passed an invalid parameter. share|improve this answer answered Oct 1 '09 at 23:59 John Millikin 124k30171199 10 The most used exceptions in constructor are ValueError and TypeError. –Denis Otkidach Oct 2 '09 at 8:41 add a comment| up vote 8 down vote I don't see any reason that it should be bad form. On the contrary, one of the things exceptions are known for doing well, as opposed to returning error codes, is that error codes usually can't be returned by constructors. So at least in languages like C++, raising exceptions is the only way to signal errors. share|improve this answer answered Oct 2 '09 at 0:01 Edan Maor 5,39294674 add a comment| up vote 8 down vote It's true that the only proper way to indicate an error in a constructo
This module never needs to be imported explicitly: the exceptions are provided in the built-in namespace as well as the
Python Exception Message
exceptions module. For class exceptions, in a try
Python Exception Constructor
statement with an except clause that mentions a particular class, that clause also handles any exception python assert classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, http://stackoverflow.com/questions/1507082/python-is-it-bad-form-to-raise-exceptions-within-init even if they have the same name. The built-in exceptions listed below can be generated by the interpreter or built-in functions. Except where mentioned, they have an "associated value" indicating the detailed cause of the error. This may be a string or a tuple containing several items of information (e.g., an error code and https://docs.python.org/2/library/exceptions.html a string explaining the code). The associated value is the second argument to the raise statement. If the exception class is derived from the standard root class BaseException, the associated value is present as the exception instance's args attribute. User code can raise built-in exceptions. This can be used to test an exception handler or to report an error condition "just like" the situation in which the interpreter raises the same exception; but beware that there is nothing to prevent user code from raising an inappropriate error. The built-in exception classes can be subclassed to define new exceptions; programmers are encouraged to derive new exceptions from the Exception class or one of its subclasses, and not from BaseException. More information on defining exceptions is available in the Python Tutorial under User-defined Exceptions. The following exceptions are only used as base classes for other exceptions. exception BaseException¶ The base class for all built-in exceptions. It i
Post #1 of 9 (4824 views) Permalink making a class return None from __init__ Hi, I have http://www.gossamer-threads.com/lists/python/python/125733 a class which makes some basic error checks in the __init__ function. Ideally, if the parameters passed to the __init__ function fail the checks I would like to return a None. But this does'nt seem to happen: class Graph: def __init__(self,v): if SOME_TEST: return None However when I test it out as: g = Graph(v) print g (where v python exception will fail) I always get <__main__.Graph instance at 0xXXXXXX> Is there any way to make the constructor return a None object? Thanks, sismex01 at hebmex Oct4,2002,1:24PM Post #2 of 9 (4808 views) Permalink making a class return None from __init__ [In reply to] > From: Rajarshi Guha [mailto:rajarshi [at] presidency] > > Hi, > I have a class which makes python raise error some basic error checks in the __init__ > function. Ideally, if the parameters passed to the __init__ > function fail > the checks I would like to return a None. But this does'nt seem to > happen: > > class Graph: > > def __init__(self,v): > if SOME_TEST: > return None > > However when I test it out as: > > g = Graph(v) > print g > > (where v will fail) I always get <__main__.Graph instance at 0xXXXXXX> > Is there any way to make the constructor return a None object? > > Thanks, > Hmmm... I believe you have a simple misunderstanding; whatever value __init__() would return is irretrievably lost (ok, enough drama), because __init__() is not called to *create* the object, but to *initialize* it, the object is already allocated by the time __init__() is called. What you *can* do is raise an exception, in which case the assignment is aborted. Good luck. -gustavo maxm at mxm Oct4,2002,1:46PM Post #3 of 9 (4806 views) Permalink making a class return None from