One of the few things that lack seriously, IMO, in C# is the power of Java checked exceptions. In Java world? things happen weirdly. Maybe it is a result of crowd intelligence and a bad side effect of open source. Often, people in J2EE world tend to believe the opposite. Anyway you see the effect in most preferred frameworks (such as today’s popular ORMs and Containers) of wrapping checked Java exceptions and rethrowing them as runtime ones.
I guess offering runtime exceptions together with compile time ones did a hole in the Java type system, but this hole was left to discipline, in a way of giving the tools and letting smart enterprise programmers decide for the right tool for the job. Things turned to happen differently in the enterprise world. Programmers abused of this freedom of choice and mainstream frameworks designers decided to dismiss and bury one of the most interesting features of the Java type system.
Why do I like Java checked exceptions? Well simply because it saves me from surprises. And I tend not to like surprises much!
The funny thing is that, in my experience, it is mostly architects that dismiss Java checked exceptions whereas Compile time exceptions are a very good asset for cleaner and bug free architecture.
I just take a look at a “standard” DAO method that gets an entity
Customer getCustomer(CustomerId id);
This method lies! what if there is no connection? what if the Id is incorrect? The signature of the methods gives quite a promise that under all circumstances it will returns a Customer. Now for any architecture this is bad. It used to be better before some popular frameworks decided to completely omit it! Before? well I used to control my architecture better!
Before these “good practices” become mainstream, imposed in mainstream frameworks, It used to be often more predictable the return type a method has. For my example, the signature would tell me that the method will either return a customer OR throws a “Dao Exception”.
Customer getCustomer(CustomerId id) throws DaoException;
No surprise. Now when I use this method, I will certainly need to handle the case when the method will return something else than a Customer. Now of course, a Java “enterprise developer” could do one of to things:
1- Out of laziness or incompetence, keep rethrowing data access exceptions up until you’ll have to deal with it up in the GUI logic (where handling an infrastructure error does not often belong)
This often sounds for me the main argument for dismissing Java Compile Time Exceptions claiming that it is a “code boilerplate”. The thing is that you’ll have to deal with these exceptions once even when you turn them into runtime. The fact of wrapping them into runtime does not eliminate them (even if I wish it did). But having them as compile time will make easy to spot where a “bad” developer did not handle the exception correctly simply by following the signature and type system. Then the solution will be to wrap them into more business friendly, context meaningful Compile Time Exceptions that need to be handled. This way the contract communicated better the result of executing a piece of logic.
This turns to be as useful for “void” return type methods. With Compile Time Exception a method can simply communicate the fact that it will either return “void” or will throw an exception to be handled.
2- Out of laziness or incompetence, frustrated developers will start “catch”ing checked exception without rethrowing them.
This one is a result of the hole in the type system that is left intentionally to leave some place for flexibility relying on discipline. Nevertheless, and before the big favor of generous frameworks I mentioned earlier, this turned out to be an easy problem to spot. Most IDEs and code analyses tools can find easily empty catch clauses and warn me about them.
I often get surprised of the limited use of Java language wealth in enterprise J2EE applications!
Good thing: C# and .Net are introducing checked exceptions together with other DbC stuff (like non null objects) in the next release. Sad thing: Java has Compile Time Exceptions since version 1, open source chose to unvalue them!


I think java uncheked exception are a good practice only in frameworks projects and in internal package of our company projects.
Checked exception is a good practice for the public part of the company projects; the public interfaces between 2 projects, the public classes used by other projects and so on…
But these good practice are quite personal ! Everything depends on our experience !
my 2 cent
Comment by Cyril Lakech — January 4, 2009 @ 12:05 pm
I used to think that having both checked and unchecked exceptions were the problem — Java should have gone with one or the other, but not both. Now, I’m not so sure of that position. I’m liking the idea of having two ways of throwing exceptions — one checked, the other unchecked. Say, “throw” and “raise”, where the former is checked and the latter isn’t. Then code that implements interfaces that don’t specify (the right type of) checked exceptions can then raise an exception as opposed to throwing it.
Comment by SJS — January 5, 2009 @ 1:18 am
Polymorphism, interfaces, versioning. If you want people to believe checked exceptions are a good thing you are going to need to at least mention the problems with them that people actually care about.
Comment by Jonathan Allen — January 5, 2009 @ 5:18 am
Have you got a link to a web page talking about the .net implementation?
Sometimes, programming in C# I feel the lack of checked exception to be aware of all the exceptions that could be thrown and write a better code (not forget one and have a big error page) without having to read all the documentation or catch ‘Exception’ without knowing which exactly exception could happened. However, obliged to catch all the exceptions could be counterproductive and leave just warning at compilation time should be the good way.
Comment by Philippe Miossec — January 5, 2009 @ 9:10 am
Philippe: The .NET implementation is just the same, without checked exceptions at all (just as though everything inherited from RuntimeException in Java, say). There’s a good discussion about the justification of this here, though:
http://www.artima.com/intv/handcuffs.html
Comment by Calum Leslie — January 5, 2009 @ 9:57 am
@Philippe
http://research.microsoft.com/en-us/projects/contracts/
Comment by Sadache — January 5, 2009 @ 9:59 am
@Jonathan
Can you please explain more or point me to a URL that defines these problems?
Comment by Sadache — January 5, 2009 @ 12:23 pm
Look at this: http://www.oracle.com/technology/pub/articles/dev2arch/2006/11/effective-exceptions.html
PS: I can only see your article comes from misunderstanding or some lack of knowledge of java enterprise development. The article really doesn’t look very well if you provide such offensive gems like – only 2 options each involving “laziness and incompetence” of java enterprise developers (good one :), link to “failure of crowd intelligence” and “abusing the freedom of choice”.
Cheers
Comment by Juraj — January 5, 2009 @ 1:00 pm
@Juraj
Not quite, you can call it free from the J2EE buzz.
I ll try to address points of the article you provided just after work.
Comment by Sadache — January 5, 2009 @ 1:39 pm
@Jurai
I frankly don’t see the issues Jonathan and your article referenced as problems in the Checked Exceptions but rather a result of lack of design and abstraction skills . Same problems will gradually appear when these exceptions are discovered at runtime, and addressed by same incompetent people. As many of the software developers do not stay long enough after the software is deployed in production, they tend to think that they got rid of exceptions by ignoring them.
Checked Exceptions only make these issues apparent. Now as for examples of IO and SQL Checked Exceptions (the main motivation of my post), I already know that there were/still are a lot of arguments against them preferring Runtime Exception, but mostly for false reasons.
One of the funny arguments is that you do not need to pollute you code with infrastructure errors that are rare to happen, well if you stay long enough to see life in production you’ll discover that they are not as rare as you thought. And guess what, The end user “catches” the exception instead of the developer, with sometimes some pretty sensitive information passed even through the World Wide Web!
Well, now with a good design, knowing at compile time that you need to handle the infrastructure errors, you create your own “infrastructure checked exception” where you wrap the kind of exception hiding sensitive information and logging what has to be logged. This way you are sending a message to the user of your service that, there is an infrastructure behind that can fail, and that he needs to think about represent the case for his service user, and so on. This is for a healthy architecture that does not delay production problems until production because they tend not to happen in dev environment.
In the same way, I don’t see how this can affect encapsulation, again in some often mentioned examples, of one file based logging, and another database log. Well you need to do an abstraction which is a logging exception that wraps logging infrastructure errors. And Checked Exceptions will help me to make sure that the end user will not receive a Logging Exception kind of error!
versioning is the same issue as in any type in the contract. I don’t guess a java programmer will change to return an int instead of an Integer because he decided. This is not an issue of Exceptions but rather a normal problem of Producer/Consumer design that you have even in dynamic languages.
I seriously think that J2EE, with the effect of mainstream frameworks, abandoned Java Checked Exceptions way too often.
Comment by Sadache — January 5, 2009 @ 8:30 pm
I much prefer C# over Java, mostly due to familiarity. That being said, I greatly wish C# had checked exceptions.
Comment by Daniel Pratt — January 6, 2009 @ 2:02 am
A couple of thoughts here. Let it be known that I’m firmly in the Unchecked exception camp. :-)
1) There’s no reason you can’t declare the throws clause on the method signature when using unchecked exceptions.
Customer getCustomer(CustomerId id) throws UncheckedDaoException;
Your method signature is now self describing and hides no details.
2) Based on the lazy/incompetent programmer scenario, I’ve seen *lots* of code that deals with exceptions by bubbling them because the code doesn’t know how to handle them.
void Foo() throws MalformedUrlException, FileNotFoundException, ClassNotFoundException, SomeCustomApplicationException {
// Crazy logic goes here.
}
Later, one of those aforementioned programmers sees that ugly mess of a throws clause and decides to clean it up:
void Foo() throws Exception {
// Same crazy logic goes here.
}
Ah, much cleaner. Unfortunately, it now tells me exactly as much information as:
void Foo() {
// Same crazy logic goes here.
}
And if that doesn’t happen, invariably the aforementioned programmer will code the caller in this fashion:
void Bar() {
try {
Foo();
}
catch(Exception e) {
// “Handle” error here.
}
}
Again, we have a situation where a generic catch all is happening when it shouldn’t be. What happens if Foo throws an IndexOutOfBoundsException? This is very likely a programming error and not simply something that we can “handle” and move on.
Comment by Brandon — January 6, 2009 @ 3:46 am
@Brandon The worst case scenario you are describing for checked exceptions is the normal situation for unchecked, the exception bubbles up. However, with Checked Exceptions the problem is very easy to spot using modern IDEs or static analyses tools but nearly impossible to detect with Runtime Exceptions!
Comment by Sadache — January 6, 2009 @ 10:13 am
AFAIK checked exceptions will not be supported in .Net 4.0 (at least not in C#, see http://code.msdn.microsoft.com/csharpfuture), where did you get that information?
The page you mentioned above is about the new design by contract features in .Net. This DbC stuff, along with automated test case generation (see the Pex tool demonstrated in the video), really looks promising, and I strongly believe that this is where we’re heading.
Compared to DbC and Pex, checked exceptions seem to be a quite primitive and inconsistent “feature”. Consider this:
private static final URL namespace = new URL(”http://example.com/specs/2009/etc”);
This code is simple, concise, and – as far as the JVM is concerned – correct. However, the java compiler will report an error due to the checked exception declared by the URL constructor. Let’s try to “fix” it:
private static final URL namespace;
static {
try {
namespace = new URL(”http://example.com/specs/2009/etc”);
} catch (MalformedURLException mue) {
throw new AssertionError(”unreachable”);
}
}
Adding those seven (!) lines of code solved the compiler issue, but now it is impossible to achieve more than 33% code coverage in regression tests, because the exception handler code can never be reached. Code coverage essentially becomes useless as a quality measure – if I get less than 100%, I’ll never know if I missed something in the unit test, or if it’s due to some darned unreachable checked exception handler. (But why bother writing unit tests at all, the compiler already told me that everything was fine, right?)
There are many more examples where checked exceptions force you to write unreachable code (String.getBytes(”UTF-8″), MessageDigest.getInstance(”MD5″), all uses of ByteArrayInput/OutputStream or StringReader/Writer…). In a language that otherwise reports unreachable code as errors, this has to be considered a bug in the language design.
In .Net 4.0, with a tool at hand to automatically devise test cases that cover all branches in the code (such as Pex), there is clearly no need for a feature that introduces unreachable code as a side effect (however promising the concept may sound in theory).
I really would like to see things like DbC and Pex in Java. However, considering how many people still believe that checked exceptions are a good idea, I don’t think that it’ll happen soon…
Comment by Karsten Blees — January 15, 2009 @ 3:27 am
Wierd post. Makes things complex. In reality all is simple covered by follwoing three statements:
- checked exceptions are business ones
- unchecked – technical, system errors
- any code any time can throw exception and developer has to take it into account. That’s Java’s nature.
Using DaoException has no much sense – it doens’t say anything, just that method can throw exception, which is known just by definition. But it adds lots of pain in neck for guys who have to think what to do with it next – add to throws or wrap with another or anything else…
Hope it helps :)
Comment by Stas — February 5, 2009 @ 10:34 am
The problem with checked exceptions in Java is that they are often ignored. And for good reason. If an SQLException occurs, for instance, it could be because of:
1. Bad SQL grammar
2. The DB doesn’t like you right now
3. The connection to the DB has an issue
4. Other
3 and 4 cannot always be resolved, and they’re usually *not* related to SQL at all. The same issue occurs with checked IOExceptions – generally, if you try and catch an IOException upon close, and one actually happens, normally, there’s nothing you can do about it – and who cares, because you’ve closed the resource and shouldn’t use it again anyways!
RuntimeExceptions, such as those used by Spring, are much more informative, and the best part is that they are optional. If all the exceptions were optional, you probably wouldn’t have the problem of naive programmers doing a try-catch and squeltching an exception at an inappropriate time. Checked exceptions force you to handle them, but as for your “Customer” method – why care about the internals? You could have a checked or runtime exception, but then every time you have to retrieve a customer you have to try catch. If you just throw a runtime exception, you’ll have the same information as a checked exception, and no one will make empty try catch blocks because they get annoyed at having to try-catch all the time (it does happen, although I generally log exceptions or place comments saying that they were intentionally ignored).
The most basic problem with checked exceptions, though, is not that they’re checked – it’s that the exception that is thrown from Java’s checked exceptions often has *nothing* to do with the actual problem – you have to dig deeper into the exception. Specific RuntimeExceptions are more easily caught when you *can* deal with the problem, and just as easily ignored when you cannot (if your customer processing method can’t get a customer, what should it do? Catch and then return, or throw the exception? I would just throw the exception, because then something would be wrong that the customer processing method cannot do anything about – and that’s what runtime exceptions do for you by default).
Comment by MF2002 — March 11, 2009 @ 5:59 pm
you mentioned you don’t like surprises. You’re right there should be no suprises when it comes to exceptional conditions but this should be done through documentation of exceptions. But the runtime behaviour you should be backuped with a good test coverage (then you see all these traces and can add error-handling code appropriatly. If done so then you don’t get suprises in production system.
My two cents also as a blog entry (I am favoring unchecked exceptions only approach):
http://www.aldana-online.de/2008/07/28/getting-rid-of-checked-exceptions-in-java/
Comment by manuel aldana — April 11, 2009 @ 8:57 am
The problem is not checked exceptions as a concept, as they obviously represents a boost to static checking at the expense of leaking abstraction (you will want to guard layer boundaries). No the problem is how they are implemented in Java. 1) You can not rethrow, only wrap 2) The hierachy is screwed, you can’t choose to only catch CheckedException while letting UncheckedExceptions bubble up 3) The Java libraries are horrible guidelines at how you should use checked exceptions.
Comment by Casper Bang — August 26, 2009 @ 1:17 pm
At first, i thought this blog was dated 2003 or so… Here’s a good article that, i find, explains quite a bit, including the popular misconceptions about exceptions. What the article does very well is explain why you don’t need a compiler alert to have no surprises.
http://constv.blogspot.com/2009/08/error-handling-and-exceptions-in-java.html
Cheers,
Alec
Comment by alec — October 4, 2009 @ 7:25 pm