<p>When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init'er to return nil?)</p>

<p>It seems to me that a constructor should fail -- and thus refuse to create an object -- if the object isn't complete. I.e., the constructor should have a contract with its caller to provide a functional and working object on which methods can be called meaningfully? Is that reasonable?</p>

[{'answer_id': 77681, 'author': 'Michael L Perry', 'author_id': 7668, 'author_profile': 'https://Stackoverflow.com/users/7668', 'pm_score': 3, 'selected': False, 'text': "<p>Because of all the trouble that a partially created class can cause, I'd say never.</p>\n\n<p>If you need to validate something during construction, make the constructor private and define a public static factory method. The method can throw if something is invalid. But if everything checks out, it calls the constructor, which is guaranteed not to throw.</p>\n"}, {'answer_id': 77698, 'author': 'blowdart', 'author_id': 2525, 'author_profile': 'https://Stackoverflow.com/users/2525', 'pm_score': 3, 'selected': False, 'text': "<p>It's always pretty dodgy, especially if you're allocating resources inside a constructor; depending on your language the destructor won't get called, so you need to manually cleanup. It depends on how when an object's lifetime begins in your language.</p>\n\n<p>The only time I've really done it is when there's been a security problem somewhere that means the object should not, rather than cannot, be created.</p>\n"}, {'answer_id': 77705, 'author': 'Sebastian Redl', 'author_id': 8922, 'author_profile': 'https://Stackoverflow.com/users/8922', 'pm_score': 9, 'selected': True, 'text': "<p>The constructor's job is to bring the object into a usable state. There are basically two schools of thought on this.</p>\n\n<p>One group favors two-stage construction. The constructor merely brings the object into a sleeper state in which it refuses to do any work. There's an additional function that does the actual initialization.</p>\n\n<p>I've never understood the reasoning behind this approach. I'm firmly in the group that supports one-stage construction, where the object is fully initialized and usable after construction.</p>\n\n<p>One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.</p>\n"}, {'answer_id': 77721, 'author': 'moonshadow', 'author_id': 11834, 'author_profile': 'https://Stackoverflow.com/users/11834', 'pm_score': 2, 'selected': False, 'text': '<p>See C++ FAQ sections <a href="http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.2" rel="nofollow noreferrer">17.2</a> and <a href="http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.4" rel="nofollow noreferrer">17.4</a>.</p>\n\n<p>In general, I have found that code that is easier to port and maintain results if constructors are written so they do not fail, and code that can fail is placed in a separate method that returns an error code and leaves the object in an inert state.</p>\n'}, {'answer_id': 77733, 'author': 'Matt Dillard', 'author_id': 863, 'author_profile': 'https://Stackoverflow.com/users/863', 'pm_score': 3, 'selected': False, 'text': '<p>It\'s reasonable for a constructor to throw an exception so long as it cleans itself up properly.  If you follow the <a href="http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization" rel="noreferrer">RAII</a> paradigm (Resource Acquisition Is Initialization) then it <strong>is</strong> quite common for a constructor to do meaningful work; a well-written constructor will in turn clean up after itself if it can\'t fully be initialized.</p>\n'}, {'answer_id': 77740, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 1, 'selected': False, 'text': '<p>Yes, if the constructor fails to build one of its internal part, it can be - by choice - its responsibility to throw (and in certain language to declare) an <a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions">explicit exception</a> , duly noted in the constructor documentation.</p>\n\n<p>This is not the only option: It could finish the constructor and build an object, but with a method \'isCoherent()\' returning false, in order to be able to signal an incoherent state (that may be preferable in certain case, in order to avoid a brutal interruption of the execution workflow due to an exception)<br>\nWarning: as said by EricSchaefer in his comment, that can bring some complexity to the unit testing (a throw can increase the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow noreferrer">cyclomatic complexity</a> of the function due to the condition that triggers it)</p>\n\n<p>If it fails because of the caller (like a null argument provided by the caller, where the called constructor expects a non-null argument), the constructor will throw an unchecked runtime exception anyway.</p>\n'}, {'answer_id': 77765, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 1, 'selected': False, 'text': '<p>Throwing an exception during construction is a great way to make your code way more complex.  Things that would seem simple suddenly become hard.  For example, let\'s say you have a stack.  How do you pop the stack and return the top value?  Well, if the objects in the stack can throw in their constructors (constructing the temporary to return to the caller), you can\'t guarantee that you won\'t lose data (decrement stack pointer, construct return value using copy constructor of value in stack, which throws, and now have a stack that just lost an item)!  This is why std::stack::pop does not return a value, and you have to call std::stack::top.</p>\n\n<p>This problem is well described <a href="http://books.google.com/books?id=mT7E5gDuW_4C&amp;pg=PA39&amp;lpg=PA39&amp;dq=exception+safe+stack+pop&amp;source=web&amp;ots=AXUQyXfWkW&amp;sig=0c3POTY82SsQ5-zNUWTzSNIoRu0&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=3&amp;ct=result#PPA32,M1" rel="nofollow noreferrer">here</a>, check Item 10, writing exception-safe code.</p>\n'}, {'answer_id': 77766, 'author': 'Luke Halliwell', 'author_id': 3974, 'author_profile': 'https://Stackoverflow.com/users/3974', 'pm_score': 2, 'selected': False, 'text': '<p>You absolutely should throw an exception from a constructor if you\'re unable to create a valid object.  This allows you to provide proper invariants in your class.</p>\n\n<p>In practice, you may have to be very careful.  Remember that in C++, the destructor will not be called, so if you throw after allocating your resources, you need to take great care to handle that properly!</p>\n\n<p><a href="http://www.gotw.ca/gotw/066.htm" rel="nofollow noreferrer">This page</a> has a thorough discussion of the situation in C++.</p>\n'}, {'answer_id': 77784, 'author': 'scubabbl', 'author_id': 9450, 'author_profile': 'https://Stackoverflow.com/users/9450', 'pm_score': 0, 'selected': False, 'text': '<p>Speaking strictly from a Java standpoint, any time you initialize a constructor with illegal values, it should throw an exception. That way it does not get constructed in a bad state.</p>\n'}, {'answer_id': 77786, 'author': 'nsanders', 'author_id': 1244, 'author_profile': 'https://Stackoverflow.com/users/1244', 'pm_score': 0, 'selected': False, 'text': '<p>To me it\'s a somewhat philosophical design decision.</p>\n\n<p>It\'s very nice to have instances which are valid as long as they exist, from ctor time onwards.  For many nontrivial cases this may require throwing exceptions from the ctor if a memory/resource allocation can\'t be made.  </p>\n\n<p>Some other approaches are the init() method which comes with some issues of its own.  One of which is ensuring init() actually gets called.  </p>\n\n<p>A variant is using a lazy approach to automatically call init() the first time an accessor/mutator gets called, but that requires any potential caller to have to worry about the object being valid.  (As opposed to the "it exists, hence it\'s valid philosophy").</p>\n\n<p>I\'ve seen various proposed design patterns to deal with this issue too.  Such as being able to create an initial object via ctor, but having to call init() to get your hands on a contained, initialized object with accesors/mutators.</p>\n\n<p>Each approach has its ups and downs; I have used all of these successfully.  If you don\'t make ready-to-use objects from the instant they\'re created, then I recommend a heavy dose of asserts or exceptions to make sure users don\'t interact before init().  </p>\n\n<p><strong>Addendum</strong></p>\n\n<p>I wrote from a C++ programmers perspective.  I also assume you are properly using the RAII  idiom to handle resources being released when exceptions are thrown.</p>\n'}, {'answer_id': 77789, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 1, 'selected': False, 'text': '<p>The usual contract in OO is that object methods do actually function.</p>\n\n<p>So as a corrolary, to never return a zombie object form a constructor/init.</p>\n\n<p>A zombie is not functional and may be missing internal components. Just a null-pointer exception waiting to happen.</p>\n\n<p>I first made zombies in Objective C, many years ago. </p>\n\n<p>Like all rules of thumb , there is an "exception".</p>\n\n<p>It is entirely possible that a <em>specific interface</em> may have a contract that says that \nthere exists a method "initialize" that is allowed to thron an exception.\nThat an object inplementing this interface may not respond correctly to any calls except property setters until initialize has been called.  I used this for device drivers in an OO operating system during the boot process, and it was workable.</p>\n\n<p>In general, you don\'t want zombie objects. In languages like Smalltalk with <strong>become</strong> things get a little fizzy-buzzy, but overuse of <em>become</em> is bad style too. <em>Become lets an object change into another object in-situ, so there is no need for envelope-wrapper(Advanced C++) or the strategy pattern(GOF).</em></p>\n'}, {'answer_id': 77797, 'author': 'Jacob Krall', 'author_id': 3140, 'author_profile': 'https://Stackoverflow.com/users/3140', 'pm_score': 6, 'selected': False, 'text': '<p><a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="noreferrer">Eric Lippert says</a> there are 4 kinds of exceptions.</p>\n\n<ul>\n<li>Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them.</li>\n<li>Boneheaded exceptions are your own darn fault, you could have prevented them and therefore they are bugs in your code.</li>\n<li>Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.</li>\n<li>And finally, exogenous exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic.</li>\n</ul>\n\n<p>Your constructor should never throw a fatal exception on its own, but code it executes may cause a fatal exception.  Something like "out of memory" isn\'t something you can control, but if it occurs in a constructor, hey, it happens.</p>\n\n<p>Boneheaded exceptions should never occur in any of your code, so they\'re right out.</p>\n\n<p>Vexing exceptions (the example is <code>Int32.Parse()</code>) shouldn\'t be thrown by constructors, because they don\'t have non-exceptional circumstances.</p>\n\n<p>Finally, exogenous exceptions should be avoided, but if you\'re doing something in your constructor that depends on external circumstances (like the network or filesystem), it would be appropriate to throw an exception.</p>\n\n<p>Reference link: <a href="https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/" rel="noreferrer">https://blogs.msdn.microsoft.com/ericlippert/2008/09/10/vexing-exceptions/</a></p>\n'}, {'answer_id': 77863, 'author': 'mlbrock', 'author_id': 9966, 'author_profile': 'https://Stackoverflow.com/users/9966', 'pm_score': 1, 'selected': False, 'text': "<p>I can't address best practice in Objective-C, but in C++ it's fine for a constructor to throw an exception. Especially as there's no other way to ensure that an exceptional condition encountered at construction is reported without resorting to invoking an isOK() method.</p>\n\n<p>The function try block feature was designed specifically to support failures in constructor memberwise initialization (though it may be used for regular functions also). It's the only way to modify or enrich the exception information which will be thrown. But because of its original design purpose (use in constructors) it doesn't permit the exception to be swallowed by an empty catch() clause.</p>\n"}, {'answer_id': 77951, 'author': 'Denice', 'author_id': 14178, 'author_profile': 'https://Stackoverflow.com/users/14178', 'pm_score': 3, 'selected': False, 'text': "<p>A constructor should throw an exception when it is unable to complete the construction of said object.</p>\n\n<p>For example, if the constructor is supposed to allocate 1024 KB of ram, and it fails to do so, it should throw an exception, this way the caller of the constructor knows that the object is not ready to be used and there is an error somewhere that needs to be fixed.</p>\n\n<p>Objects that are half-initialised and half-dead just cause problems and issues, as there really is no way for the caller to know. I'd rather have my constructor throw an error when things go wrong, than having to rely on the programming to run a call to the isOK() function which returns true or false.</p>\n"}, {'answer_id': 78020, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': "<p>Throw an exception if you're unable to initialize the object in the constructor, one example are illegal arguments.</p>\n\n<p>As a general rule of thumb an exception should always be thrown as soon as possible, as it makes debugging easier when the source of the problem is closer to the method signaling something is wrong.</p>\n"}, {'answer_id': 82373, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': "<p>There is <strong>generally</strong> nothing to be gained by divorcing object initialization from construction. RAII is correct, a successful call to the constructor should either result in a fully initialized live object or it should fail, and <strong>ALL</strong> failures at any point in any code path should always throw an exception. You gain nothing by use of a separate init() method except additional complexity at some level. The ctor contract should be either it returns a functional valid object or it cleans up after itself and throws.</p>\n\n<p>Consider, if you implement a separate init method, you <strong>still</strong> have to call it. It will still have the potential to throw exceptions, they still have to be handled and they virtually always have to be called immediately after the constructor anyway, except now you have 4 possible object states instead of 2 (IE, constructed, initialized, uninitialized, and failed vs just valid and non-existent). </p>\n\n<p>In any case I've run across in 25 years of OO development cases where it seems like a separate init method would 'solve some problem' are design flaws. If you don't need an object NOW then you shouldn't be constructing it now, and if you do need it now then you need it initialized. KISS should always be the principle followed, along with the simple concept that the behavior, state, and API of any interface should reflect WHAT the object does, not HOW it does it, client code should not even be aware that the object has any kind of internal state that requires initialization, thus the init after pattern violates this principle.</p>\n"}, {'answer_id': 85467, 'author': 'Tegan Mulholland', 'author_id': 16431, 'author_profile': 'https://Stackoverflow.com/users/16431', 'pm_score': 0, 'selected': False, 'text': "<p>Using factories or factory methods for all object creation, you can avoid invalid objects without throwing exceptions from constructors. The creation method should return the requested object if it's able to create one, or null if it's not. You lose a little bit of flexibility in handling construction errors in the user of a class, because returning null doesn't tell you what went wrong in the object creation. But it also avoids adding the complexity of multiple exception handlers every time you request an object, and the risk of catching exceptions you shouldn't handle.</p>\n"}, {'answer_id': 389525, 'author': 'Nick', 'author_id': 44741, 'author_profile': 'https://Stackoverflow.com/users/44741', 'pm_score': 2, 'selected': False, 'text': "<p>If you are writing UI-Controls (ASPX, WinForms, WPF, ...) you should avoid throwing exceptions in the constructor because the designer (Visual Studio) can't handle them when it creates your controls. Know your control-lifecycle (control events) and use lazy initialization wherever possible.</p>\n"}, {'answer_id': 5006212, 'author': 'stevex', 'author_id': 8831, 'author_profile': 'https://Stackoverflow.com/users/8831', 'pm_score': 2, 'selected': False, 'text': '<p>Note that if you throw an exception in an initializer, you\'ll end up leaking if any code is using the <code>[[[MyObj alloc] init] autorelease]</code> pattern, since the exception will skip the autorelease.</p>\n\n<p>See this question:</p>\n\n<p><a href="https://stackoverflow.com/questions/5005852/how-do-you-prevent-leaks-when-raising-an-exception-in-init">How do you prevent leaks when raising an exception in init?</a></p>\n'}, {'answer_id': 42913195, 'author': 'cwharris', 'author_id': 696056, 'author_profile': 'https://Stackoverflow.com/users/696056', 'pm_score': 4, 'selected': False, 'text': '<p>As far as I can tell, no-one is presenting a fairly obvious solution which embodies the best of both one-stage and two-stage construction.</p>\n\n<p><strong>note:</strong> This answer assumes C#, but the principles can be applied in most languages.</p>\n\n<p>First, the benefits of both:</p>\n\n<h2>One-Stage</h2>\n\n<p>One-stage construction benefits us by preventing objects from existing in an invalid state, thus preventing all sorts of erroneous state management and all the bugs which come with it. However, it leaves some of us feeling weird because we don\'t want our constructors to throw exceptions, and sometimes that\'s what we need to do when initialization arguments are invalid.</p>\n\n<pre><code>public class Person\n{\n    public string Name { get; }\n    public DateTime DateOfBirth { get; }\n\n    public Person(string name, DateTime dateOfBirth)\n    {\n        if (string.IsNullOrWhitespace(name))\n        {\n            throw new ArgumentException(nameof(name));\n        }\n\n        if (dateOfBirth &gt; DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n        {\n            throw new ArgumentOutOfRangeException(nameof(dateOfBirth));\n        }\n\n        this.Name = name;\n        this.DateOfBirth = dateOfBirth;\n    }\n}\n</code></pre>\n\n<h2>Two-Stage via validation method</h2>\n\n<p>Two-stage construction benefits us by allowing our validation to be executed outside of the constructor, and therefore prevents the need for throwing exceptions within the constructor. However, it leaves us with "invalid" instances, which means there\'s state we have to track and manage for the instance, or we throw it away immediately after heap-allocation. It begs the question: Why are we performing a heap allocation, and thus memory collection, on an object we don\'t even end up using?</p>\n\n<pre><code>public class Person\n{\n    public string Name { get; }\n    public DateTime DateOfBirth { get; }\n\n    public Person(string name, DateTime dateOfBirth)\n    {\n        this.Name = name;\n        this.DateOfBirth = dateOfBirth;\n    }\n\n    public void Validate()\n    {\n        if (string.IsNullOrWhitespace(Name))\n        {\n            throw new ArgumentException(nameof(Name));\n        }\n\n        if (DateOfBirth &gt; DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n        {\n            throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n        }\n    }\n}\n</code></pre>\n\n<h2>Single-Stage via private constructor</h2>\n\n<p>So how can we keep exceptions out of our constructors, and prevent ourselves from performing heap allocation on objects which will be immediately discarded? It\'s pretty basic: we make the constructor private and create instances via a static method designated to perform an instantiation, and therefore heap-allocation, only <strong><em>after</em></strong> validation.</p>\n\n<pre><code>public class Person\n{\n    public string Name { get; }\n    public DateTime DateOfBirth { get; }\n\n    private Person(string name, DateTime dateOfBirth)\n    {\n        this.Name = name;\n        this.DateOfBirth = dateOfBirth;\n    }\n\n    public static Person Create(\n        string name,\n        DateTime dateOfBirth)\n    {\n        if (string.IsNullOrWhitespace(Name))\n        {\n            throw new ArgumentException(nameof(name));\n        }\n\n        if (dateOfBirth &gt; DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n        {\n            throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n        }\n\n        return new Person(name, dateOfBirth);\n    }\n}\n</code></pre>\n\n<h2>Async Single-Stage via private constructor</h2>\n\n<p>Aside from the aforementioned validation and heap-allocation prevention benefits, the previous methodology provides us with another nifty advantage: async support. This comes in handy when dealing with multi-stage authentication, such as when you need to retrieve a bearer token before using your API. This way, you don\'t end up with an invalid "signed out" API client, and instead you can simply re-create the API client if you receive an authorization error while attempting to perform a request.</p>\n\n<pre><code>public class RestApiClient\n{\n    public RestApiClient(HttpClient httpClient)\n    {\n        this.httpClient = new httpClient;\n    }\n\n    public async Task&lt;RestApiClient&gt; Create(string username, string password)\n    {\n        if (username == null)\n        {\n            throw new ArgumentNullException(nameof(username));\n        }\n\n        if (password == null)\n        {\n            throw new ArgumentNullException(nameof(password));\n        }\n\n        var basicAuthBytes = Encoding.ASCII.GetBytes($"{username}:{password}");\n        var basicAuthValue = Convert.ToBase64String(basicAuthBytes);\n\n        var authenticationHttpClient = new HttpClient\n        {\n            BaseUri = new Uri("https://auth.example.io"),\n            DefaultRequestHeaders = {\n                Authentication = new AuthenticationHeaderValue("Basic", basicAuthValue)\n            }\n        };\n\n        using (authenticationHttpClient)\n        {\n            var response = await httpClient.GetAsync("login");\n            var content = response.Content.ReadAsStringAsync();\n            var authToken = content;\n            var restApiHttpClient = new HttpClient\n            {\n                BaseUri = new Uri("https://api.example.io"), // notice this differs from the auth uri\n                DefaultRequestHeaders = {\n                    Authentication = new AuthenticationHeaderValue("Bearer", authToken)\n                }\n            };\n\n            return new RestApiClient(restApiHttpClient);\n        }\n    }\n}\n</code></pre>\n\n<p>The downsides of this method are few, in my experience.</p>\n\n<p>Generally, using this methodology means that you can no longer use the class as a DTO because deserializing to an object without a public default constructor is hard, at best. However, if you were using the object as a DTO, you shouldn\'t really be validating the object itself, but rather invaliding the values on the object as you attempt to use them, since technically the values aren\'t "invalid" with regards to the DTO.</p>\n\n<p>It also means that you\'ll end up creating factory methods or classes when you need to allow an IOC container to create the object, since otherwise the container won\'t know how to instantiate the object. However, in a lot of cases the factory methods end up being one of <code>Create</code> methods themselves.</p>\n'}, {'answer_id': 46705088, 'author': 'Raedwald', 'author_id': 545127, 'author_profile': 'https://Stackoverflow.com/users/545127', 'pm_score': 0, 'selected': False, 'text': "<p>The best advice I've seen about exceptions is to throw an exception if, and only if, the alternative is failure to meet a post condition or to maintain an invariant.</p>\n\n<p>That advice replaces an unclear subjective decision (is it a <em>good idea</em>) with a technical, precise question based on design decisions (invariant and post conditions) you should already have made.</p>\n\n<p>Constructors are just a particular, but not special, case for that advice. So the question becomes, what invariants should a class have? Advocates of a separate initialization method, to be called after construction, are suggesting that the class has two or more <em>operating mode</em>, with an <em>unready</em> mode after construction and at least one <em>ready</em> mode, entered after initialization. That is an additional complication, but acceptable if the class has multiple operating modes anyway. It is hard to see how that complication is worthwhile if the class would otherwise not have operating modes.</p>\n\n<p>Note that pushing set up into a separate initialization method does not enable you to avoid exceptions being thrown. Exceptions that your constructor might have thrown will now be thrown by the initialization method. All the useful methods of your class will have to throw exceptions if they are called for an uninitialized object.</p>\n\n<p>Note also that avoiding the possibility of exceptions being thrown by your constructor is troublesome, and in many cases <em>impossible</em> in many standard libraries. This is because the designers of those libraries believe that throwing exceptions from constructors is a good idea. In particular, any operation that attempts to acquire a non shareable or finite resource (such as allocating memory) can fail, and that failure is typically indicated in OO languages and libraries by throwing an exception.</p>\n"}, {'answer_id': 49033272, 'author': 'Denise Skidmore', 'author_id': 2091951, 'author_profile': 'https://Stackoverflow.com/users/2091951', 'pm_score': 1, 'selected': False, 'text': "<p>I'm not sure that any answer can be entirely language-agnostic.  Some languages handle exceptions and memory management differently.  </p>\n\n<p>I've worked before under coding standards requiring exceptions never be used and only error codes on initializers, because developers had been burned by the language poorly handling exceptions.  Languages without garbage collection will handle heap and stack very differently, which may matter for non RAII objects.  It is important though that a team decide to be consistent so they know by default if they need to call initializers after constructors.  All methods (including constructors) should also be well documented as to what exceptions they can throw, so callers know how to handle them.</p>\n\n<p>I'm generally in favor of a single-stage construction, as it's easy to forget to initialize an object, but there are plenty of exceptions to that.</p>\n\n<ul>\n<li>Your language support for exceptions isn't very good.</li>\n<li>You have a pressing design reason to still use <code>new</code> and <code>delete</code></li>\n<li>Your initialization is processor intensive and should run async to the thread that created the object.</li>\n<li>You are creating a DLL that may be throwing exceptions outside it's interface to an application using a different language.  In this case it may not be so much an issue of not throwing exceptions, but making sure they are caught before the public interface.  (You can catch C++ exceptions in C#, but there are hoops to jump through.)</li>\n<li>Static constructors (C#)</li>\n</ul>\n"}, {'answer_id': 51277298, 'author': 'Ashley', 'author_id': 5370163, 'author_profile': 'https://Stackoverflow.com/users/5370163', 'pm_score': 1, 'selected': False, 'text': '<p>The OP\'s question has a "language-agnostic" tag... this question cannot be safely answered the same way for all languages/situations.</p>\n\n<p>The following C# example\'s class hierarchy throws in class B\'s constructor, skipping an immediate call to class A\'s <code>IDisposeable.Dispose</code> upon exit of the main\'s <code>using</code>, skipping explicit disposal of class A\'s resources.</p>\n\n<p>If, for example, class A had created a <code>Socket</code> at construction, connected to a network resource, such would likely still be the case after the <code>using</code> block (a relatively hidden anomaly). </p>\n\n<pre><code>class A : IDisposable\n{\n    public A()\n    {\n        Console.WriteLine("Initialize A\'s resources.");\n    }\n\n    public void Dispose()\n    {\n        Console.WriteLine("Dispose A\'s resources.");\n    }\n}\n\nclass B : A, IDisposable\n{\n    public B()\n    {\n        Console.WriteLine("Initialize B\'s resources.");\n        throw new Exception("B construction failure: B can cleanup anything before throwing so this is not a worry.");\n    }\n\n    public new void Dispose()\n    {\n        Console.WriteLine("Dispose B\'s resources.");\n        base.Dispose();\n    }\n}\nclass C : B, IDisposable\n{\n    public C()\n    {\n        Console.WriteLine("Initialize C\'s resources. Not called because B throws during construction. C\'s resources not a worry.");\n    }\n\n    public new void Dispose()\n    {\n        Console.WriteLine("Dispose C\'s resources.");\n        base.Dispose();\n    }\n}\n\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        try\n        {\n            using (C c = new C())\n            {\n            }\n        }\n        catch\n        {           \n        }\n\n        // Resource\'s allocated by c\'s "A" not explicitly disposed.\n    }\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/77639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14050/']