For a number of years now I have been unable to get a decent answer to the following question: why are some developers so against checked exceptions? I have had numerous conversations, read things on blogs, read what Bruce Eckel had to say (the first person I saw speak out against them).
I am currently writing some new code and paying very careful attention to how I deal with exceptions. I am trying to see the point of view of the "we don't like checked exceptions" crowd and I still cannot see it.
Every conversation I have ends with the same question going unanswered... let me set it up:
In general (from how Java was designed),
- Error is for things that should never be caught (VM has a peanut allergy and someone dropped a jar of peanuts on it)
- RuntimeException is for things that the programmer did wrong (programmer walked off the end of an array)
- Exception (except RuntimeException) is for things that are out of the programmer's control (disk fills up while writing to the file system, file handle limit for the process has been reached and you cannot open any more files)
- Throwable is simply the parent of all of the exception types.
A common argument I hear is that if an exception happens then all the developer is going to do is exit the program.
Another common argument I hear is that checked exceptions make it harder to refactor code.
For the "all I am going to do is exit" argument I say that even if you are exiting you need to display a reasonable error message. If you are just punting on handling errors then your users won't be overly happy when the program exits without a clear indication of why.
For the "it makes it hard to refactor" crowd, that indicates that the proper level of abstraction wasn't chosen. Rather than declare a method throws an IOException, the IOException should be transformed into an exception that is more suited for what is going on.
I don't have an issue with wrapping Main with catch(Exception) (or in some cases catch(Throwable) to ensure that the program can exit gracefully - but I always catch the specific exceptions I need to. Doing that allows me to, at the very least, display an appropriate error message.
The question that people never reply to is this:
If you throw RuntimeException subclasses instead of Exception subclasses then how do you know what you are supposed to catch?
If the answer is catch Exception then you are also dealing with programmer errors the same way as system exceptions. That seems wrong to me.
If you catch Throwable then you are treating system exceptions and VM errors (and the like) the same way. That seems wrong to me.
If the answer is that you catch only the exceptions you know are thrown then how do you know what ones are thrown? What happens when programmer X throws a new exception and forgot to catch it? That seems very dangerous to me.
I would say that a program that displays a stack trace is wrong. Do people who don't like checked exceptions not feel that way?
So, if you don't like checked exceptions can you explain why not AND answer the question that doesn't get answered please?
Edit: I am not looking for advice on when to use either model, what I am looking for is why people extend from RuntimeException because they don't like extending from Exception and/or why they catch an exception and then rethrow a RuntimeException rather than add throws to their method. I want to understand the motivation for disliking checked exceptions.
Indeed, checked exceptions on the one hand increase robustness and correctness of your program (you're forced to make correct declarations of your interfaces -the exceptions a method throws are basically a special return type). On the other hand you face the problem that, since exceptions "bubble up", very often you need to change a whole lot of methods (all the callers, and the callers of the callers, and so on) when you change the exceptions one method throws.
Checked exceptions in Java do not solve the latter problem; C# and VB.NET throw out the baby with the bathwater.
A nice approach that takes the middle road is described in this OOPSLA 2005 paper (or the related technical report.)
In short, it allows you to say:
method g(x) throws like f(x)
, which means that g throws all the exceptions f throws. Voila, checked exceptions without the cascading changes problem.Although it is an academic paper, I'd encourage you to read (parts of) it, as it does a good job of explaining what the benefits and downsides of checked exceptions are.
This article is the best piece of text on exception handling in Java I have ever read.
It favours unchecked over checked exceptions but this choice is explained very thouroughly and based on strong arguments.
I don't want to cite too much of the article content here (it's best to read it as a whole) but it covers most of arguments of unchecked exceptions advocates from this thread. Especially this argument (which seems to be quite popular) is covered:
The author "responses":
And the main thought or article is:
So if "nobody knew it was even possible for this error to occur" there is something wrong with that project. Such exception should be handled by at least the most generic exception handler (e.g. the one that handles all Exceptions not handled by more specific handlers) as author suggests.
So sad not many poeple seems to discover this great article :-(. I recommend wholeheartly everyone who hesitates which approach is better to take some time and read it.
Well, it's not about displaying a stacktrace or silently crashing. It's about being able to communicate errors between layers.
The problem with checked exceptions is they encourage people to swallow important details (namely, the exception class). If you choose not to swallow that detail, then you have to keep adding throws declarations across your whole app. This means 1) that a new exception type will affect lots of function signatures, and 2) you can miss a specific instance of the exception you actually -want- to catch (say you open a secondary file for a function that writes data to a file. The secondary file is optional, so you can ignore its errors, but because the signature
throws IOException
, it's easy to overlook this).I'm actually dealing with this situation now in an application. We repackaged almost exceptions as AppSpecificException. This made signatures really clean and we didn't have to worry about exploding
throws
in signatures.Of course, now we need to specialize the error handling at the higher levels, implementing retry logic and such. Everything is AppSpecificException, though, so we can't say "If an IOException is thrown, retry" or "If ClassNotFound is thrown, abort completely". We don't have a reliable way of getting to the real exception because things get repackaged again and again as they pass between our code and third-party code.
This is why I'm a big fan of the exception handling in python. You can catch only the things you want and/or can handle. Everything else bubbles up as if you rethrew it yourself (which you have done anyways).
I've found, time and time again, and throughout the project I mentioned, that exception handling falls into 3 categories:
Anders speaks about the pitfalls of checked exceptions and why he left them out of C# in episode 97 of Software Engineering radio.
I've read a lot about exception handling, even if (most of the time) I cannot really say I'm happy or sad about the existence of checked exceptions this is my take : checked exceptions in low-level code(IO, networking, OS, etc) and unchecked exceptions in high-level APIs/application level.
Even if there is not so easy to draw a line between them, I find that it is really annoying/difficult to integrate several APIs/libraries under the same roof without wrapping all the time lots of checked exceptions but on the other hand, sometime it is useful/better to be forced to catch some exception and provide a different one which makes more sense in the current context.
The project I'm working on takes lots of libraries and integrates them under the same API, API which is completely based on unchecked exceptions.This frameworks provides a high-level API which in the beginning was full of checked exceptions and had only several unchecked exceptions(Initialization Exception, ConfigurationException, etc) and I must say was not very friendly. Most of the time you had to catch or re-throw exceptions which you don't know how to handle, or you don't even care(not to be confused with you should ignore exceptions), especially on the client side where a single click could throw 10 possible (checked) exceptions.
The current version(3rd one) uses only unchecked exceptions, and it has a global exception handler which is responsible to handle anything uncaught. The API provides a way to register exception handlers, which will decide if an exception is considered an error(most of the time this is the case) which means log & notify somebody, or it can mean something else - like this exception, AbortException, which means break the current execution thread and don't log any error 'cause it is desired not to. Of course, in order to work out all custom thread must handle the run() method with a try {...} catch(all).
public void run() {
}
This is not necessary if you use the WorkerService to schedule jobs(Runnable, Callable, Worker), which handles everything for you.
Of course this is just my opinion, and it might not be the right one, but it looks like a good approach to me. I will see after I will release the project if what I think it is good for me, it is good for others too... :)
My writeup on c2.com is still mostly unchanged from its original form: CheckedExceptionsAreIncompatibleWithVisitorPattern
In summary:
Visitor Pattern and its relatives are a class of interfaces where the indirect caller and interface implementation both know about an exception but the interface and direct caller form a library that cannot know.
The fundamental assumption of CheckedExceptions is all declared exceptions can be thrown from any point that calls a method with that declaration. The VisitorPattern reveals this assumption to be faulty.
The final result of checked exceptions in cases like these is a lot of otherwise useless code that essentially removes the compiler's checked exception constraint at runtime.
As for the underlying problem:
My general idea is the top-level handler needs to interpret the exception and display an appropriate error message. I almost always see either IO exceptions, communication exceptions (for some reason APIs distinguish), or task-fatal errors (program bugs or severe problem on backing server), so this should not be too hard if we allow a stack trace for a severe server problem.