<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Clément Elbaz on Medium]]></title>
        <description><![CDATA[Stories by Clément Elbaz on Medium]]></description>
        <link>https://medium.com/@clement_elbaz?source=rss-56e7a5d159df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7151SImAQnVg-Msx.png</url>
            <title>Stories by Clément Elbaz on Medium</title>
            <link>https://medium.com/@clement_elbaz?source=rss-56e7a5d159df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:20:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@clement_elbaz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[We need to talk about exceptions.]]></title>
            <link>https://medium.com/@clement_elbaz/we-need-to-talk-about-exceptions-e96bc9ceb76b?source=rss-56e7a5d159df------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96bc9ceb76b</guid>
            <dc:creator><![CDATA[Clément Elbaz]]></dc:creator>
            <pubDate>Sat, 16 Aug 2014 20:28:40 GMT</pubDate>
            <atom:updated>2014-10-21T13:06:52.722Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>(and logging)</blockquote><p>Hello. My name is Clément Elbaz, I am from Rennes, France and I am a Java developer during the day. I’ve been part of a few projects during my career. Some had strong code quality standards. Some had not. I’ve spent many hours with many people discussing good coding practices, in Java and in general.</p><p>In those kind of conversations, some topics arise every time.<br>This one does not. I’ve never seen it being addressed in project coding guidelines. I’ve rarely seen lead developers giving clear, explicit instructions about it on the projects I’ve worked on.</p><p>This topic is <strong>exception management</strong>.</p><p>Exceptions are an ubiquitous aspect of Java. Every CS student that toyed three hours with the language has handled a few of them already. Accomplished programmers deal with them on an hourly basis.</p><p>A lot of languages have similar exception systems, like Ruby, PHP, C++, and many others. The examples in this article use Java but the notions described here are very much language agnostic.</p><p>Let’s get back to basics for a bit.</p><p><a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html">Oracle documentation</a> use the following definition to describe Java exceptions :</p><blockquote><strong>Definition: </strong>An <em>exception </em>is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.</blockquote><p>This is a <em>hell of a lot</em> interesting.<br>Most programmers associates “exceptions” with notions like “problems” or “errors” or “things frakking up” in general. The official definition doesn’t talk at all about problems or errors. It says <em>“disruption from the normal flow of the program”</em>.</p><p>I said this article would be about exception management.<br>In “exception management”, you have two words. Exceptions, and… management.</p><p>Let see how we manage some exceptions !</p><p>But first, let see how DEFINITELY NOT to handle them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*eM39DUL-cMOaUwGyz2uh9w.png" /><figcaption>Don’t do this.<br>Seriously, don’t.</figcaption></figure><p>Take a look at this piece of code.<br>Looks familiar, isn’t it ?<br>I’ve seen this kind of coding plenty of time in a lot of codebases. I’ve myself been guilty of a few of these ones in my younger years.</p><p>This is usually written by a novice programmer whose train of thoughts usually goes like this:</p><blockquote>“Oh god oh god oh my god, I have no idea what I’m doing but I don’t want my code to crash the application, I really don’t want that, no no no no”</blockquote><p>And the solution they come up with is to make sure their method won’t ever throw an exception. Never. Ever.</p><p>Two problems with this approach :</p><ul><li>The method has a lot of chance to introduce null pointers when it is called, making it very likely to crash the application anyways. People calling this method without doing a null check will get in bad shape pretty quickly. Introducing null pointers is usually a lot worse than throwing an exception.</li><li>If the method does return a null pointer, even if we successfully acknowledge it we have no way to know if this was the result of a technical problem (with the database), or because there is no user in the database (a functional problem). But the two underlying causes are <em>really, really</em> different.</li></ul><p><strong>Checked vs Errors vs Runtime</strong></p><p>As a reminder, in Java you can define and throw three types of exceptions :</p><ul><li>Checked exceptions thrown by a method should be <em>specified</em> in the method signature, and any other method calling it must be able to <em>handle</em> it (by catching it or throwing it too). Absence of compliance to this rule will result in a compilation error. When dealing with checked exception, you need a try-catch block.</li><li>Errors and runtime exceptions do not need to be specified and can be thrown at any time. Errors are usually associated with an external failure while runtime exceptions (like the infamous <em>NullPointerException</em>) are usually associated with an internal problems.</li></ul><p>My personal take on the thing : never <em>ever </em>throw errors and runtime exceptions unless you absolutely know what you’re doing. If you are several people on the same codebase, even if <strong>you</strong> know what <strong>you</strong>’re doing you do not necessarily know what the other guys are up to. So don’t do it.</p><p>Even external failures should be handled through checked exceptions. If you throw Errors, you have a good chance of not catching them and going through a hard failure, that is, a plain old crash of you program. If you encounter a checked exception you can not recover from, you can at least fail gracefully (with a pretty error message, for example).</p><p>99% of real life applications can not afford a hard failure. So don’t form habits that can only be sustainable 1% of the time.</p><p>An exception thrown manually should be dealt with manually at compile time. Never at run time.</p><p>Some languages do provide runtime exceptions but no compile-time exception mechanism. I do not feel competent talking about them or giving advice about them. A compile-time exception mechanism is an important feature of a language and I personally would not try developing a complex system without it.</p><p>But let’s get back to Java.</p><p><strong>A better way to do things</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*DFyGg8a_uGZ1u5XKG27rZA.png" /><figcaption>This is better.</figcaption></figure><p>And a variation I’ve also seen quite often :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*waBXnRaPpRfKTzhhyjNtLg.png" /><figcaption>This too.</figcaption></figure><p>These two versions are a lot better. They also have their shortcomings.</p><p>But first things first.</p><p>This is a lot better because :</p><ul><li>We <em>acknowledge</em> things can fail. If any technical problem arise, we abstract the problem but we do not hide it away.</li><li>We never return a null pointer. Either a correct value can be returned, or we throw an exception that must be handled by the caller. I like the <em>NoUserException</em> version better for this reason : the caller must handle a very explicit edge case and can not compile its code without having at least to think about it.</li></ul><p><strong>The Functional vs Technical problem</strong></p><p>I’ve been a fan of the Functional vs Technical division of exceptions and used it for a long time, but there is a fundamental flaw in this way of thinking.</p><p>In short :</p><blockquote>The functional or technical nature of an exception is <strong>context-dependent</strong>.</blockquote><p>Think about it for a bit. A functional problem in a layer of a system <em>can actually be viewed as technical</em> when viewed from another layer.</p><p>Let say you send a query to a database server, and this query contains a syntax error.</p><p>The database server will detect the error and fail. But from its point of view it will be functional : it received a wrong query, so nothing can be done with it.</p><p>But from the point of view of your application, sending a erroneous query<em> is very much</em> a technical problem.</p><p>So you have a problem that can be functional from one side and technical from another.</p><p>Another example.</p><p>Let say someone connect to your web application with a valid cookie that retrieves a valid session.<br>In this session, there is a userId. However, when getting the user from the database, you encounter a <em>NoUserException</em>, a functional problem. But missing a user at this stage is very much a technical problem.</p><p>So, technical or functional ?</p><blockquote><strong><em>Obi-Wan:</em></strong> “Luke, you’re going to find that many of the truths we cling to (like the functional or technical nature of a problem) depend greatly on our own point of view.”</blockquote><p>I’ve been thinking about it for a while and came up with another way of viewing things.</p><p><strong>The explainability chain</strong></p><p>The basic idea is that some exceptions are <em>explainable </em>and some others are <em>unexplainable</em>.</p><p><em>NoUserException </em>is a perfectly explainable problem : you searched for a user, everything went fine but there was no user to be found.</p><p>On the other hand, murky exceptions like SQLException or ParserException are <em>unexplainable</em>. That means the best thing to do is to abstract them as “something failed but we don’t know how or why.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*xUWfAQXqR7WuiK-TDq0Wow.png" /><figcaption>This is my favorite way to do things.</figcaption></figure><p>Let say you write a LoginService that invoke UserService in the following way :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*VeqBC1kjrMKpRStbkPcl4Q.png" /><figcaption>Going one layer up</figcaption></figure><p>If something goes wrong in UserService, an exception is thrown. This exception is encapsulated by another exception in LoginService, creating an <em>exception chain</em>.</p><p>If an exception chain is <em>fully explainable (</em>like <em>NoUserException </em>=&gt; <em>LoginFailedException</em>), then you’ve got a fully explainable problem and you can act on it. In the case of a failed login, you just have to display a pretty message to the user.</p><p><strong>What to do with your exception chain</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*7zcZs9Fjs3mJiC84mpIHLw.png" /><figcaption>Our last layer, a typical servlet</figcaption></figure><p>Once you got “back to the surface” with a full exception chain, at some point you need to handle it.</p><ul><li>If you have a fully explainable exception chain, what to do is probably self-explanatory. A LoginFailedException is handled by displaying a message to the user.</li><li>An unexplainable exception chain creates two problems : we need to log the problem and, if a user request is pending, we need to inform the user that a problem arised. You don’t try to recover from an unexplainable exception chain excepted in one specific case explained later.</li></ul><p>Something very important :</p><p><strong><em>When</em></strong><em> and </em><strong><em>how</em></strong><em> to handle an unexplainable exception chain should be decided </em><strong><em>project wide</em></strong><em> by the lead developer.</em></p><p>If you are not the lead developer of a project, you should not have to guess. You should ask or read your project coding guidelines. Conversely, if you are the lead dev, you should have a very precise answer for your colleagues. And even better, you should write it down in the project coding guidelines.</p><p>Fully explainable exception chains do not need technical logging. A supervision/security log might be emitted, but again <em>this is a decision that should be decided depending on the context</em>.<br>A fully explainable exception chain, like a failed login attempt is an <em>unusual</em> but still <em>normal</em> course of events, so it might be worth a note if your application has strong security requirements.</p><p>But an unexplainable exception chain require a lot more decisions.</p><ul><li>What to log — generally, as much things as possible, with a big caveat explained below.</li><li>What to say to the user (if there is one) — generally, just “something failed, sorry” will be enough. However if you trust your user (for instance, an employee of a big company using an internal system), you might give him some information, like an error code or even the full stack trace in order to help IT support nailing the problem quickly.</li></ul><p>If you don’t have any guidelines on this (and most projects have none), you’re usually fine with as much information as possible in the log and as few as possible for the user.</p><p>But defining what to say and what not to say can be helpful for support.</p><p>As a side note, here is how Google handles it with Youtube :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8sORpNrASNSig-xQUDj21g.png" /></figure><p>This data blob (which is probably encrypted) is undecipherable for mere mortals like us but surely contains very useful information for Youtube engineers. This is a great solution, though it requires thorough coordination between the lead dev and his team.</p><p><strong>Logging — is it that easy ?</strong></p><p>Logging seems simple on the surface, but most projects just scratch the surface of it.</p><p>I’ll only talk about <em>technical </em>logging here : something unexplainable just happened and we need to store information for future investigations. Supervision or security logging deal with daily incidents and are simpler (or at least, beyond the scope of this article).</p><p>Remember that technical logging happen in a <em>degraded situation</em> : <strong>something just failed and we have no idea what nor why</strong>.</p><p>Logging is the act of storing outside the application an information currently inside of it. Where we store it is irrelevant : on the filesystem, in a database, on a distant server, etc, all of these things <em>can</em> and <em>will</em> fail.</p><ul><li>If we log on the filesystem (like a typical Log4J configuration), we may run out of space. If we do not have access to a full hard drive (because we partitioned or virtualized the environment), we may have a limited space for logs.<br>If your database goes down for several minutes, you may have thousands of events to log and disk space can be filled very quickly.</li><li>If we have multiple application servers, keeping logs on individual servers can become troublesome when investigating a problem.</li><li>If we log on a distant device, like a database or a distant server, we won’t be able to log anything if our connection to it is lost. If the logging server goes down, no one can log anything. If some application server loses its network connection, it can not warn about it.</li><li>If you log on your application database, if the database goes down you’ve got two problems : you have an unexplainable failure and you generate another one while trying to log about it. Don’t do it.<br>(However it is fine to do some <em>supervision logging </em>on your application database, but as I said we are only dealing with technical logs here)</li></ul><p><strong>A logging strategy</strong></p><p>Your application should have a <em>logging strategy</em>. It can be simple but it can not be missing.</p><p>A simple logging strategy is a plain circular logging configuration, in Log4J for instance : store logs on the filesystem and erase older logs as newer ones replace them. You still have to carefully decide the size of the circular buffer to make sure you have room for investigations if a big problem (that consumes a lot of logging space) occurs.</p><p>An elaborated logging strategy that would work better with multiple applications servers could be :</p><ul><li>Try to log on a centralized logging server.</li><li>If the logging server does not acknowledge, log on the filesystem.</li></ul><p><strong>High availability and unexplainable failures</strong></p><p>The only time you should try to recover from an unexpected problem is when your application has a <em>high availability</em> requirement.<br>In that case, you may catch an unexplainable exception chain, <em>log it first</em>, then go to your <em>plan B</em>.</p><p>For instance :</p><ul><li>You got an UnexplainableDatabaseException while trying to write to a master database</li><li>Log it through a project-defined logging strategy.</li><li>Redo the write on a slave database.</li><li>If another unexplainable problem arise this time, log it and fail once and for all.</li></ul><p>High availability is a really big decision that must be decided project-wide on the very beginning. It implies a lot of things far beyond the scope of this article. Trying to recover from an unexplainable exception is only a tiny aspect of it.</p><p><strong>A note about performance</strong></p><p>If you use exceptions as part of your control flow, you will probably create a lot of them. Classic exception creation can be quite costly because of the filling of a stack trace every time.</p><p>Fortunately, <a href="http://blogs.atlassian.com/2011/05/if_you_use_exceptions_for_path_control_dont_fill_in_the_stac/">a simple trick</a> from the Atlassian team can mitigate most of the performance cost of exceptions. You might consider implement it in an “ExplainableException” superclass if performance is a consideration. Unexplainable exceptions should definitely keep their stack traces though.</p><p><strong>Conclusion</strong></p><p>A seemingly simple topic like exception management can actually become quite complex when you think about it in details.</p><p>In summary :</p><ul><li>Consider throwing exceptions for edge cases, especially instead of null values.</li><li>Run time exceptions are bad.</li><li>Consider dividing your exceptions between the <em>explainable</em> ones and the <em>unexplainable</em> ones.</li><li>Exception handling should be decided project wide.</li><li>The logging strategy should be decided project wide.</li></ul><p>That’s it ! I hope you enjoyed reading this article as much as I did writing it ☺</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96bc9ceb76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>