Python Throw 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 python __init__ try except policies of this site About Us Learn more about Stack Overflow the
Python Exception Types
company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users
Python Raise Custom Exception
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 other. Join them; it only takes
Python Raise Valueerror
a minute: Sign up Bad Practice to run code in constructor thats likely to fail? up vote 12 down vote favorite 4 my question is rather a design question. In Python, if code in your "constructor" fails, the object ends up not being defined. Thus: someInstance = MyClass("test123") #lets say that constructor throws an exception someInstance.doSomething() # will fail, name someInstance python raise exception with message not defined. I do have a situation though, where a lot of code copying would occur if i remove the error-prone code from my constructor. Basically my constructor fills a few attributes (via IO, where a lot can go wrong) that can be accessed with various getters. If I remove the code from the contructor, i'd have 10 getters with copy paste code something like : is attribute really set? do some IO actions to fill the attribute return the contents of the variable in question I dislike that, because all my getters would contain a lot of code. Instead of that I perform my IO operations in a central location, the constructor, and fill all my attributes. Whats a proper way of doing this? python oop exception-handling constructor share|improve this question edited Jun 7 '09 at 9:07 lispmachine 3,05711526 asked Jun 2 '09 at 8:05 Tom 1,34742034 ok, I'll remember that, I'm still new here and want to give credit to the people who spend their valuable time, trying to answer my questions, I really appreciate it! –Tom Jun
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 python rethrow exception more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags python exception message Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, python exception constructor helping each other. Join them; it only takes a minute: Sign up Handle exception in __init__ up vote 9 down vote favorite 3 Is it fine to raise an exception in __init__ in python? I have this http://stackoverflow.com/questions/938426/bad-practice-to-run-code-in-constructor-thats-likely-to-fail piece of code: class VersionManager(object): def __init__(self, path): self._path = path if not os.path.exists(path): os.mkdir(path) myfunction(path) The second line can potentially result in an exception. In that case the object will not be init'ed properly. Is there a better way to handle situations where code in __init__ might throw an exception? EDIT Added a call to a function after os.mkdir Added a check to see if directory exists python exception share|improve this question edited Nov 18 http://stackoverflow.com/questions/20059766/handle-exception-in-init '13 at 23:49 asked Nov 18 '13 at 22:57 Abhishek Chanda 1,0871235 Not only is the object not initialized properly, with no exception handler at best the caller of VersionManager(path) can hope catch the exception and have no instance, at all. –Martijn Pieters♦ Nov 18 '13 at 22:59 2 os.mkdir is a bit of a special case, because it throws an exception in a case that for many users is not an error -- when the directory already exists. So you might want to handle that case explicitly, aside from the question of whether your __init__ function should raise exceptions in general. –Steve Jessop Nov 18 '13 at 23:43 Thanks for reminding me of that. However, I am more curious about a OSError which can be caused by a permission denied. –Abhishek Chanda Nov 18 '13 at 23:48 2 If VersionManager needs the directory to exist in order to work, and its __init__ function fails to create the directory, then allowing the exception to propagate is entirely reasonable. The meaning of throwing an exception from __init__ is, "I cannot make this object work, so I will not let you have the object". Or perhaps more formally, "I cannot establish the invariants for this object". Although again creating a file or directory a special case for a class invariant. There's usually
your question and get tips & solutions from a community of 418,626 IT Pros & Developers. It's quick & easy. __init__ method and raising exceptions P: https://bytes.com/topic/python/answers/43335-__init__-method-raising-exceptions n/a NavyJay I have a simple for-loop, which instantiates a class object each iteration. As part of my class constructor, __init__(), I check for valid input settings. If there is a problem https://en.wikibooks.org/wiki/Python_Programming/Exceptions with this iteration, I want to abort the loop, but equivalently 'continue' on in the for-loop. I can't use 'break' or 'continue' in a class method, nor can I return a boolean python exception value from __init__() to check for errors within the for-loop. How would I be able to stop the current iteration and continue with the next after reporting an error? Jay Jul 18 '05 #1 Post Reply Share this Question 5 Replies P: n/a Leif K-Brooks NavyJay wrote: I have a simple for-loop, which instantiates a class object each iteration. As part of my class constructor, python throw error __init__(), I check for valid input settings. If there is a problem with this iteration, I want to abort the loop, but equivalently 'continue' on in the for-loop. I can't use 'break' or 'continue' in a class method, nor can I return a boolean value from __init__() to check for errors within the for-loop. How would I be able to stop the current iteration and continue with the next after reporting an error? You have the right idea in the subject header: raise an exception. Something along the lines of this: class Foo(object): def __init__(self, value): if value > 10: raise ValueError("Value must be under 10, was %s." % value) else: self.value = value for value in [1, 4, 10, 7, 15, 13, 6, 3]: try: obj = Foo(value) except ValueError, ex: print str(ex) continue # Do stuff with obj here Jul 18 '05 #2 P: n/a Vikram > I can't use 'break' or 'continue' in a class method, nor can I return a boolean value from __init__() to check for errors within the for-loop. How would I be able to stop the current iteration and continue with the next after reporting an
is a signal that an error or other unusual condition has occurred. There are a number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. You can also define your own exceptions. Contents 1 Raising exceptions 2 Catching exceptions 2.1 Custom Exceptions 2.2 Trying over and over again 3 Recovering and continuing with finally 4 Built-in exception classes 5 Exotic uses of exceptions Raising exceptions[edit] Whenever your program attempts to do something erroneous or meaningless, Python raises exception to such conduct: >>> 1 / 0 Traceback (most recent call last): File "