<p>Unchecked exceptions are alright if you want to handle every failure the same way, for example by logging it and skipping to the next request, displaying a message to the user and handling the next event, etc. If this is my use case, all I have to do is catch some general exception type at a high level in my system, and handle everything the same way.</p>

<p>But I want to recover from specific problems, and I'm not sure the best way to approach it with unchecked exceptions. Here is a concrete example.</p>

<p>Suppose I have a web application, built using Struts2 and Hibernate. If an exception bubbles up to my "action", I log it, and display a pretty apology to the user. But one of the functions of my web application is creating new user accounts, that require a unique user name. If a user picks a name that already exists, Hibernate throws an <code>org.hibernate.exception.ConstraintViolationException</code> (an unchecked exception) down in the guts of my system. I'd really like to recover from this particular problem by asking the user to choose another user name, rather than giving them the same "we logged your problem but for now you're hosed" message.</p>

<p>Here are a few points to consider:</p>

<ol>
<li>There a lot of people creating accounts simultaneously. I don't want to lock the whole user table between a "SELECT" to see if the name exists and an "INSERT" if it doesn't. In the case of relational databases, there might be some tricks to work around this, but what I'm really interested in is the general case where pre-checking for an exception won't work because of a fundamental race condition. Same thing could apply to looking for a file on the file system, etc.</li>
<li>Given my CTO's propensity for drive-by management induced by reading technology columns in "Inc.", I need a layer of indirection around the persistence mechanism so that I can throw out Hibernate and use Kodo, or whatever, without changing anything except the lowest layer of persistence code. As a matter of fact, there are several such layers of abstraction in my system. How can I prevent them from leaking in spite of unchecked exceptions?</li>
<li>One of the declaimed weaknesses of checked exceptions is having to "handle" them in every call on the stack&mdash;either by declaring that a calling method throws them, or by catching them and handling them. Handling them often means wrapping them in another checked exception of a type appropriate to the level of abstraction. So, for example, in checked-exception land, a file-system&ndash;based implementation of my UserRegistry might catch <code>IOException</code>, while a database implementation would catch <code>SQLException</code>, but both would throw a <code>UserNotFoundException</code> that hides the underlying implementation. How do I take advantage of unchecked exceptions, sparing myself of the burden of this wrapping at each layer, without leaking implementation details?</li>
</ol>

[{'answer_id': 33509, 'author': 'Nick', 'author_id': 1490, 'author_profile': 'https://Stackoverflow.com/users/1490', 'pm_score': 2, 'selected': False, 'text': '<p>I like to repackage exceptions between the "tiers" of my application, so for example a DB-specific exception is repackaged inside of another exception which is meaningful in the context of my application (of course, I leave the original exception as a member so I don\'t clobber the stack trace).</p>\n\n<p>That said, I think that a non-unique user name is not an "exceptional" enough situation to warrant a throw.  I\'d use a boolean return argument instead.  Without knowing much about your architecture, it\'s hard for me to say anything more specific or applicable.</p>\n'}, {'answer_id': 33514, 'author': 'codeLes', 'author_id': 3030, 'author_profile': 'https://Stackoverflow.com/users/3030', 'pm_score': 1, 'selected': False, 'text': "<p>Since you're currently using hibernate the easiest thing to do is just check for that exception and wrap it in either a custom exception or in a custom result object you may have setup in your framework.  If you want to ditch hibernate later just make sure you wrap this exception in only 1 place, the first place you catch the exception from hibernate, that's the code you'll probably have to change when you make a switch anyway, so if the catch is in one place then the additional overhead is almost zilch.</p>\n\n<p>help?</p>\n"}, {'answer_id': 33542, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 1, 'selected': False, 'text': '<p>I agree with Nick. Exception you described is not really "unexpected exception" so you should design you code accordingly taking possible exceptions into account.</p>\n\n<p>Also I would recommend to take a look at documentation of Microsoft Enterprise Library <a href="http://msdn.microsoft.com/en-us/library/cc511522.aspx" rel="nofollow noreferrer">Exception Handling Block</a> it has a nice outline of error handling patterns.</p>\n'}, {'answer_id': 33564, 'author': 'Craig Walker', 'author_id': 3488, 'author_profile': 'https://Stackoverflow.com/users/3488', 'pm_score': 5, 'selected': True, 'text': '<p>IMO, wrapping exceptions (checked or otherwise) has several benefits that are worth the cost:</p>\n\n<p>1) It encourages you to think about the failure modes for the code you write. Basically, you have to consider the exceptions that the code you call may throw, and in turn you\'ll consider the exceptions you\'ll throw for the code that calls yours.</p>\n\n<p>2) It gives you the opportunity to add additional debugging information into the exception chain. For instance, if you have a method that throws an exception on a duplicate username, you might wrap that exception with one that includes additional information about the circumstances of the failure (for example, the IP of the request that provided the dupe username) that wasn\'t available to the lower-level code. The cookie trail of exceptions may help you debug a complex problem (it certainly has for me).</p>\n\n<p>3) It lets you become implementation-independent from the lower level code. If you\'re wrapping exceptions and need to swap out Hibernate for some other ORM, you only have to change your Hibernate-handling code. All the other layers of code will still be successfully using the wrapped exceptions and will interpret them in the same way, even though the underlying circumstances have changed. Note that this applies even if Hibernate changes in some way (ex: they switch exceptions in a new version); it\'s not just for wholesale technology replacement.</p>\n\n<p>4) It encourages you use different classes of exceptions to represent different situations. For example, you may have a DuplicateUsernameException when the user tries to reuse a username, and a DatabaseFailureException when you can\'t check for dupe usernames due to a broken DB connection. This, in turn, lets you answer your question ("how do I recover?") in flexible and powerful ways. If you get a DuplicateUsernameException, you may decide to suggest a different username to the user. If you get a DatabaseFailureException, you may let it bubble up to the point where it displays a "down for maintenance" page to the user and send off a notification email to you. Once you have custom exceptions, you have customizeable responses -- and that\'s a good thing.</p>\n'}, {'answer_id': 33651, 'author': 'Cem Catikkas', 'author_id': 3087, 'author_profile': 'https://Stackoverflow.com/users/3087', 'pm_score': 0, 'selected': False, 'text': '<p>You can catch unchecked exceptions without needing to wrap them. For example, the following is valid Java.</p>\n\n<pre><code>try {\n    throw new IllegalArgumentException();\n} catch (Exception e) {\n    System.out.println("boom");\n}\n</code></pre>\n\n<p>So in your action/controller you can have a try-catch block around the logic where the Hibernate call is made. Depending on the exception you can render specific error messages. </p>\n\n<p>But I guess in your today it could be Hibernate, and tomorrow SleepLongerDuringWinter framework. In this case you need to pretend to have your own little ORM framework that wraps around the third party framework. This will allow you to wrap any framework specific exceptions into more meaningful and/or checked exceptions that you know how to make better sense of.  </p>\n'}, {'answer_id': 39769, 'author': 'Jan Soltis', 'author_id': 3997, 'author_profile': 'https://Stackoverflow.com/users/3997', 'pm_score': 1, 'selected': False, 'text': '<ol>\n<li><p>The question is not really related to checked vs. unchecked debate, the same applies to both exception types.</p></li>\n<li><p>Between the point where the ConstraintViolationException is thrown and the point, where we want to handle the violation by displaying a nice error message is a large number of method calls on the stack that should abort immediately and shouldn\'t care about the problem. That makes the exception mechanism the right choice as opposed to redesigning the code from exceptions to return values.</p></li>\n<li><p>In fact, using an unchecked exception instead of a checked exception is a natural fit, since we really want all intermediate methods on the call stack to <em>ignore</em> the exception and <em>not handle it</em> .</p></li>\n<li><p>If we want to handle the "unique name violation" only by displaying a nice error message (error page) to the user, there\'s not really a need for a specific DuplicateUsernameException. This will keep the number of exception classes low. Instead, we can create a MessageException that can be reused in many similar scenarios.</p>\n\n<p>As soon as possible we catch the ConstraintViolationException and convert it to a MessageException with a nice message. It\'s important to convert it soon, when we can be sure, it\'s really the "unique user name constraint" that was violated and not some other constraint.</p>\n\n<p>Somewhere close to the top level handler, just handle the MessageException in a different way. Instead of "we logged your problem but for now you\'re hosed" simply display the message contained in the MessageException, no stack trace.</p>\n\n<p>The MessageException can take some additional constructor parameters, such as a detailed explanation of the problem, available next action (cancel, go to a different page), icon (error, warning)...</p></li>\n</ol>\n\n<p>The code may look like this</p>\n\n<pre><code>// insert the user\ntry {\n   hibernateSession.save(user);\n} catch (ConstraintViolationException e) {\n   throw new MessageException("Username " + user.getName() + " already exists. Please choose a different name.");\n}\n</code></pre>\n\n<p>In a totally different place there\'s a top exception handler</p>\n\n<pre><code>try {\n   ... render the page\n} catch (MessageException e) {\n   ... render a nice page with the message\n} catch (Exception e) {\n   ... render "we logged your problem but for now you\'re hosed" message\n}\n</code></pre>\n'}, {'answer_id': 40636, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 0, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/questions/33497/how-do-i-recover-from-an-unchecked-exception#39769">@Jan</a> Checked versus unchecked is a central issue here. I question your supposition (#3) that the exception should be ignored in intervening frames. If I do that, I will end up with an implementation-specific dependency in my high-level code. If I replace Hibernate, catch blocks throughout my application will have to be modified. Yet, at the same time, if I catch the exception at a lower level, I\'m not receiving much benefit from using an unchecked exception.</p>\n\n<p>Also, the scenario here is that I want to catch a specific logical error and change the flow of the application by re-prompting the user for a different ID. Simply changing the displayed message is not good enough, and the ability to map to different messages based on exception type is built into Servlets already.</p>\n'}, {'answer_id': 73601, 'author': 'VonC', 'author_id': 6309, 'author_profile': 'https://Stackoverflow.com/users/6309', 'pm_score': 0, 'selected': False, 'text': '<p>@erikson</p>\n\n<p>Just to add food to your thoughts:</p>\n\n<p>Checked versus unchecked is also <a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions">debated here</a></p>\n\n<p>The usage of unchecked exceptions is compliant with the fact they are used IMO for exception <em>caused by the caller of the function</em> (and the caller can be several layers above that function, hence the necessity for other frames to ignore the exception)</p>\n\n<p>Regarding your specific issue, you should catch the unchecked exception at high level, and encapsulate it, as said by @Kanook in your own exception, without displaying the callstack (as mentionned by @Jan Soltis )</p>\n\n<p>That being said, if the underlying technology changes, that will indeed have an impact on those catch() already present in your code, and that does not answer your latest scenario.</p>\n'}, {'answer_id': 75250, 'author': 'user13229', 'author_id': 13229, 'author_profile': 'https://Stackoverflow.com/users/13229', 'pm_score': 2, 'selected': False, 'text': '<p>See <a href="http://www.blueskyline.com/ErrorPatterns/A2-LongshawWoods6.pdf" rel="nofollow noreferrer">Patterns for Generation, Handling and\nManagement of Errors</a></p>\n\n<p>From the Split Domain and Technical Errors pattern</p>\n\n<blockquote>\n  <p>A technical error should never cause a\n  domain error to be generated (never\n  the twain should meet). When a\n  technical error must cause business\n  processing to fail, it should be\n  wrapped as a SystemError. </p>\n  \n  <p>Domain errors should always start from a\n  domain problem and be handled by\n  domain code. </p>\n  \n  <p>Domain errors should\n  pass "seamlessly" through technical\n  boundaries. It may be that such errors\n  must be serialized and re-constituted\n  for this to happen. Proxies and\n  facades should take responsibility for\n  doing this. </p>\n  \n  <p>Technical errors should\n  be handled in particular points in the\n  application, such as boundaries (see\n  Log at Distribution Boundary). </p>\n  \n  <p>The\n  amount of context information passed\n  back with the error will depend on how\n  useful this will be for subsequent\n  diagnosis and handling (figuring out\n  an alternative strategy). You need to\n  question whether the stack trace from\n  a remote machine is wholly useful to\n  the processing of a domain error\n  (although the code location of the\n  error and variable values at that time\n  may be useful)</p>\n</blockquote>\n\n<p>So, wrap the hibernate exception at the boundary to hibernate with an unchecked domain exception such as a "UniqueUsernameException", and let that bubble up all the way to the handler of it.  Make sure to javadoc the thrown exception even though it isn\'t a checked exception!</p>\n'}]
['https://Stackoverflow.com/questions/33497', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3474/']