<?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:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>SoftThink</title>
	<atom:link href="http://rattigan.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://rattigan.wordpress.com</link>
	<description>Musings on Software Development</description>
	<lastBuildDate>Wed, 19 Dec 2007 12:54:10 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='rattigan.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/8a991287962a27f29772273f46323eee?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>SoftThink</title>
		<link>http://rattigan.wordpress.com</link>
	</image>
			<item>
		<title>Exception handling in Java</title>
		<link>http://rattigan.wordpress.com/2007/12/17/exception-handling-in-java/</link>
		<comments>http://rattigan.wordpress.com/2007/12/17/exception-handling-in-java/#comments</comments>
		<pubDate>Mon, 17 Dec 2007 19:19:53 +0000</pubDate>
		<dc:creator>rattigan</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[class loader]]></category>
		<category><![CDATA[error handling]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[exception handling]]></category>
		<category><![CDATA[stack trace]]></category>

		<guid isPermaLink="false">http://rattigan.wordpress.com/2007/12/17/exception-handling-in-java/</guid>
		<description><![CDATA[On every project I&#8217;ve worked on, one of the first things I have to do is work out why an exception was thrown. Usually, that first error message doesn&#8217;t contain enough information to help me solve the problem. At this point I congratulate the previous developer of the system on getting so far with such [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rattigan.wordpress.com&blog=2324040&post=5&subd=rattigan&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>On every project I&#8217;ve worked on, one of the first things I have to do is work out why an exception was thrown. Usually, that first error message doesn&#8217;t contain enough information to help me solve the problem. At this point I congratulate the previous developer of the system on getting so far with such sloppy error handling.</p>
<p>After congratulating myself, I move on to reviewing the project&#8217;s approach to exception handling. I like to do this globally if possible, to ensure that the approach is consistent throughout the project, and so that I can have reasonably expect to see the information I need next time something goes wrong.</p>
<p>Good exception handling and reporting is critical to the success of any software project. Since the bulk of a project&#8217;s lifetime is spent in bug fixing and maintenance, good error reporting can make this phase of a project much less time consuming that it might be. With a stack trace, I can immediately tell where the fault occurred, and who was calling that code. In most cases, that&#8217;s enough information to understand the problem.</p>
<p>I&#8217;ve completely refactored the exception handling of a couple of medium-sized projects; in doing so, I&#8217;ve observed a few rules of thumb make this process a breeze if followed. I&#8217;ll try to summarize them here:</p>
<p><strong>Don&#8217;t swallow nested exceptions</strong></p>
<p>Change this:</p>
<pre>
    try { ... }
    catch (Foo e) { <strong>throw Bar()</strong> }
</pre>
<p>to this:</p>
<pre>
    try { ... }
    catch (Foo e) { <strong>throw Bar(e)</strong> }
</pre>
<p>The first exception thrown is always the most important for software developer; it provides information about the underlying cause and location of a failure. When you discard it this way, determining what happened is next to impossible.</p>
<p>In case you&#8217;re wondering, the following is not a good substitute:</p>
<pre>
    try { ... }
    catch (Foo e) { <strong>throw Bar(e.getMessage())</strong> }
</pre>
<p>Tempting, but count yourself lucky if you get any useful information this way; you&#8217;ll probably get a vague message, or perhaps nothing at all. And you just lost the most useful piece of information: the stack trace of the underlying error.</p>
<p><span id="more-5"></span><br />
<strong>Don&#8217;t add messages to exceptions when you have nothing to say</strong></p>
<p>Change this:</p>
<pre>
    try { ... }
    catch (Foo e) { <strong>throw Bar("Error", e)</strong> }
</pre>
<p>to this:</p>
<pre>
    try { ... }
    catch (Foo e) { <strong>throw Bar(e)</strong> }
</pre>
<p>If you are simply converting an exception from one type to another, there may be no need to add information. You might be changing a caught exception into a runtime exception, or into an application or library specific exception type. In such cases, there&#8217;s usually no reason to add more information; the exception itself can provide this information.</p>
<p>Doing this has two benefits: you don&#8217;t have to read useless information when something goes wrong, and you don&#8217;t have to spend time thinking of something useless to say.</p>
<p><strong>Don&#8217;t catch exceptions if you don&#8217;t need to</strong></p>
<p>Change this:</p>
<pre>
    <strong>try {</strong> foo() <strong>}</strong>
    <strong>catch (Foo e) { throw Foo(e) }</strong>
</pre>
<p>to this:</p>
<pre>
    foo()
</pre>
<p>If you&#8217;re going to throw an exception of the same type as that you caught, and you aren&#8217;t adding any useful information&#8230; don&#8217;t handle the exception at all.</p>
<p><strong>Use checked exceptions sparingly</strong></p>
<p>Change this:</p>
<pre>
    g() throws <strong>Gee</strong> { throw <strong>Gee()</strong> }

    f() <strong>throws Foo</strong> {
        <strong>try {</strong> g() <strong>}
        catch (Gee e) { throw Foo(e) }</strong>
    }
</pre>
<p>to this:</p>
<pre>
    g() throws <strong>RuntimeBar</strong> { throw <strong>RuntimeBar()</strong> }

    f() { g() }
</pre>
<p>A fatal error is a fatal error is a fatal error. When you force the caller of a function to handle a problem they can&#8217;t solve, all you&#8217;re doing is making them churn out pointless exception handling code. </p>
<p>If there&#8217;s a significant chance that when you throw an exception, the caller is not going to be able to continue, make sure that it&#8217;s a runtime exception. That way, most callers won&#8217;t have to write redundant exception handling code; they&#8217;ll still have the option, but they won&#8217;t be forced to.</p>
<p>Checked exceptions are less useful than you might think. When you call a method that declares and exception, this does not mean that the method cannot throw anythig else, just that it can only throw <em>checked</em> exceptions of that type. Even that rule can be <a href="http://andersnoras.com/blogs/anoras/archive/2007/07/16/look-mom-no-checked-exception.aspx">broken</a>. And of course, that method is free to throw all manner of unchecked exceptions. Do you trust it not to?</p>
<p>What this means is that if you really want to catch everything that a method can throw, you always have to catch <code>Throwable</code>.</p>
<p><strong>Use a single exception type for all application code</strong></p>
<p>Change this:</p>
<pre>
    g() throws <strong>Gee</strong> { ... }

    f() throws <strong>Foo</strong> {
        <strong>try {</strong> g() <strong>}
        catch (Gee e) { throw Foo(e) }</strong>
    }
</pre>
<p>to this:</p>
<pre>
    g() throws <strong>Bar</strong> { ... }

    f() throws <strong>Bar</strong> {
        g()
    }
</pre>
<p>This is great way to eliminate large amounts of unnecessary exception handling code. If you really need to have differentiated exceptions, you can either add an identifying property to the exception class, or use inheritance, so that callers can just handle the base exception class if desired.</p>
<p><strong>Reuse existing exception types where appropriate</strong></p>
<p>Change this:</p>
<pre>
    doSomethingDatabasey() throws <strong>DatabaseException</strong> {
        <strong>try {</strong>
            ... // jdbc code
        <strong>} catch (SQLException e) {
            throw new DatabaseException(e)
        }</strong>
    }

    f() throws Foo {
        try {
            ... // jdbc code
            doSomethingDatabasey()
        } catch (SQLException e) {
            throw Foo(e)
        } <strong>catch (DatabaseException f) {
            throw Foo(f)
        }</strong>
    }
</pre>
<p>to this:</p>
<pre>
    doSomethingDatabasey() throws <strong>SQLException</strong> {
        ... // jdbc code
    }

    f() throws Foo {
        try {
            ... // jdbc code
            doSomethingDatabasey()
        } catch (SQLException e) {
            throw Foo(e)
        }
    }
</pre>
<p>If you&#8217;re augmenting or reusing an existing library or API, reuse it&#8217;s exception types. This lets you substitute and mix calls from both interfaces without having to change or add new exception handling code.</p>
<p><strong>Java built-in exception reporting is inadequate &#8211; don&#8217;t use it</strong></p>
<p>Change this:</p>
<pre>
    main() {
        doSomething()
    }
</pre>
<p>to this:</p>
<pre>
    main() {
        <strong>try {</strong>
            doSomething()
        <strong>} catch (Throwable e) {</strong>
            reportException() // you'll need to write this...
        <strong>}</strong>
    }
</pre>
<p>Java&#8217;s built in exception handling does a pretty poor job of distilling the information contained in an exception into a form that is useful for debugging. This is what happens when you call <code>getStackTrace()</code> or <code>printStackTrace()</code>, or when an exception is never caught and propagates out of <code>main()</code>. This should never happen, which means you should be sure to catch <em>all</em> exceptions in main; the only way to do this is to catch <code>Throwable</code>.</p>
<p>So what do we want from our exception reports? Stack traces, messages, nested exception information, bean properties&#8230; That&#8217;s a topic for another post!</p>
<p><strong>Provide stack traces</strong><br />
While we don&#8217;t want to scare users by showing them a full stack trace, it is essential to be able to get this information for troubleshooting purposes. Depending on the type of application, you approach may vary.</p>
<p><em>Logging:</em> Ensuring that all exceptions are logged in detail is essential in all applications. By logging stack traces, you can show basic error information that might enable a user to resolve the issue, while still having the ability to get a stack trace if necessary. Exceptions that occur while logging should be sent to <code>stderr</code>.</p>
<p><em>Verbose flag:</em> An easily flipped switch to ask for verbose error output can work adequately in many cases. By default, only display the exception message. If this is clear, it might be enough for the user to resolve the problem. If the problem is a bug, rather than a configuration issue or temporary system outage, setting the verbose flag should provide full information to the development team. The downside of this approach is that is requires the bug to be easily reproducible, as a stack trace cannot be obtained for the original exception.</p>
<p><em>Details button:</em> In a GUI or web interface, you can allow users to drill down to a stack trace if necessary, by providing a button for accessing this detail. Typically though, you can&#8217;t expect a user to glean anything from a stack trace, so perhaps a &#8217;send to support&#8217; link would be more useful here.</p>
<p><strong>Provide class loader information</strong><br />
In complex environments, such as an application container, dependencies are often problematic. When reporting and exception, it can be very useful to provide as much information as you can about the class loader hierarchy, and where each of those class loaders locates the classes involved in the stack trace. In my experience this can save a lot of time when troubleshooting dependency problems.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/rattigan.wordpress.com/5/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/rattigan.wordpress.com/5/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/rattigan.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/rattigan.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/rattigan.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/rattigan.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/rattigan.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/rattigan.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/rattigan.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/rattigan.wordpress.com/5/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/rattigan.wordpress.com/5/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/rattigan.wordpress.com/5/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=rattigan.wordpress.com&blog=2324040&post=5&subd=rattigan&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://rattigan.wordpress.com/2007/12/17/exception-handling-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e81569bf2c6b6e493d0e6ceeb3981ed2?s=96&#38;d=identicon" medium="image">
			<media:title type="html">Richard</media:title>
		</media:content>
	</item>
	</channel>
</rss>