<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Burcu Dogan&#039;s Blog &#187; java</title>
	<atom:link href="http://burcudogan.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://burcudogan.com</link>
	<description>Burcu Dogan is a software engineer, a technologist and an open source enthusiastic.</description>
	<lastBuildDate>Thu, 05 Jan 2012 08:01:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='burcudogan.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Burcu Dogan&#039;s Blog &#187; java</title>
		<link>http://burcudogan.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://burcudogan.com/osd.xml" title="Burcu Dogan&#039;s Blog" />
	<atom:link rel='hub' href='http://burcudogan.com/?pushpress=hub'/>
		<item>
		<title>Would you Like to Throw Exceptions from a Constructor?</title>
		<link>http://burcudogan.com/2009/03/26/would-you-like-to-throw-exceptions-from-a-constructor/</link>
		<comments>http://burcudogan.com/2009/03/26/would-you-like-to-throw-exceptions-from-a-constructor/#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 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=burcudogan.com&amp;blog=21440216&amp;post=144&amp;subd=burcudo&amp;ref=&amp;feed=1" width="1" height="1" />]]></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>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/burcudo.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/burcudo.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/burcudo.wordpress.com/144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=burcudogan.com&amp;blog=21440216&amp;post=144&amp;subd=burcudo&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://burcudogan.com/2009/03/26/would-you-like-to-throw-exceptions-from-a-constructor/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e7526ec3e801f8ba99f6746498a154a6?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">thejbf</media:title>
		</media:content>
	</item>
	</channel>
</rss>
