<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Observed by Burcu Dogan &#187; java</title>
	<atom:link href="http://blog.burcudogan.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.burcudogan.com</link>
	<description>burcu dogan&#039;s monthly routine. caution: risk of overdose.</description>
	<lastBuildDate>Wed, 08 Sep 2010 20:37:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Would you Like to Throw Exceptions from a Constructor?</title>
		<link>http://blog.burcudogan.com/144/</link>
		<comments>http://blog.burcudogan.com/144/#comments</comments>
		<pubDate>Fri, 27 Mar 2009 00:40:33 +0000</pubDate>
		<dc:creator>Burcu Dogan</dc:creator>
				<category><![CDATA[Regular]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[constructors]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://blog.burcudogan.com/?p=144</guid>
		<description><![CDATA[Throwing an exception from a constructor has always been an arguable issue between my friends after a few beers of joy. It firstly came to me on an exam where question was asking me to design a class which lets not more than n number of instances to be constructed. Not using the most straight-forward [...]]]></description>
			<content:encoded><![CDATA[<p>Throwing an exception from a constructor has always been an arguable issue between my friends after a few beers of joy. It firstly came to me on an exam where question was asking me to design a class which lets <em>not more than n number of instances to be constructed.</em></p>
<p>Not using the most straight-forward trick to have a private constructor, I decided to invoke an exception from constructor if there exists more than n instances of that particular class. Luckily, I was coding in Java and had the comfort of a managed environment under the belt. My answer wasn’t graded thankfully but this case became a major concern and I decided to make several experiments back in the old days.</p>
<p>According to what I have seen while debugging, Java simply assigns a number of nulls or zeros to all of the fields of the class unless constructor is successfully executed. Additionally, right after an exception is thrown from a constructor, a null reference is returned and the newly created invalid instance starts to wait for the <strong>garbage collector</strong> to pick it up and remove the useless object from memory permanently. In short terms, a new instance is created although platform tends to murder it quickly in silent.</p>
<h2>What about Unmanaged Platforms?</h2>
<p>It was nice to see somebody was taking care of such exceptional situations but what would you do if you were alone? Fault tolerance isn’t just catching all exceptions: (from slides of <a href="http://www.research.att.com/~bs">Bjarne Stroustrup</a>)</p>
<ol>
<li>The program must be <strong>in a valid state</strong> after an exception is caught</li>
<li><em>Resource leaks must be avoided</em></li>
</ol>
<p>This will become a problem where memory management is all up to you. You will have to remove and cleanup resources after an exception has been thrown, otherwise it will cause a leakage in memory and you will have created a zombie object hanging around memory &#8212; attached to the mother thread.</p>
<h2>Cleaning Up the Mess of C++</h2>
<p>An object is not even an object once its constructor finished successfully. So, better try to release resources inside the constructor before you throw an exception. In this case, I&#8217;m always using a <strong>double-exception throwing pattern</strong> that I made up and passionately using it in similar situations I face.</p>
<p>Let&#8217;s ask the complier! Two lines of code is always more representative than 10 lines of words. Here below, I&#8217;ve written a class called &#8220;Foo&#8221;, not functional but dangerous and an exception &#8220;StreamInitException&#8221; was decided to be thrown if there happens a problem while longStreamChar is being initialized. Right after we allocate 10k bytes for longStreamChar, <strong>BOOM</strong>! Someone pushed the wrong button, somebody shut down the database or trouble makers&#8217; spirits are near. Don&#8217;t try to catch it inside the constructor and see what happens. Many orphan kids, once we named them as longStreamChar, are all around and we can&#8217;t even access them.</p>
<pre>#include &lt;iostream&gt;

struct StreamInitException {
    StreamInitException(char * m){ message = m; }
    char * message;
};

class Foo {
    public:
        Foo(){
            try {
                this-&gt;initCharStream();
            } catch(StreamInitException * ex) {
                this-&gt;~Foo(); //release resources
                throw ex; // exception originally thrown by initCharStream
            }
        }

        ~Foo(){
            if(this-&gt;longCharStream)
            delete this-&gt;longCharStream;
        }

        void initCharStream(){
            //create a long char array of 10k
            this-&gt;longCharStream = (char*)malloc(10000);
            throw new StreamInitException("Error occurred during init.");
        }
    private:
        char * longCharStream;
    };

int main(){

    Foo * foo = NULL;

    try{
        foo = new Foo;
    } catch(StreamInitException * ex){
        std::cout &lt;&lt; ex-&gt;message &lt;&lt; std::endl;
    }

    return 0;

}</pre>
<p>Therefore, I&#8217;m handling init related bad moments of the object inside the constructor, deallocate memory etc. and re-throw the same exception finally after I get the hold of the control. Seems acceptable!</p>
<p class="warning">Consequently, <strong>I have a final question</strong>: do you prefer to throw an exception from constructors or search for other workarounds such as assigning the workload to a separate method called Init()?</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.burcudogan.com/144/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
