The case against checked exceptions

2018-12-31 23:23发布

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.

30条回答
低头抚发
2楼-- · 2018-12-31 23:36

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.

查看更多
不再属于我。
3楼-- · 2018-12-31 23:36

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:

Take the case when the exception was thrown somewhere at the bottom of the API layers and just bubbled up because nobody knew it was even possible for this error to occur, this even though it was a type of error that was very plausible when the calling code threw it (FileNotFoundException for example as opposed to VogonsTrashingEarthExcept... in which case it would not matter if we handle it or not since there is nothing left to handle it with).

The author "responses":

It is absolutely incorrect to assume that all runtime exceptions should not be caught and allowed to propagate to the very "top" of the application. (...) For every exceptional condition that is required to be handled distinctly - by the system/business requirements - programmers must decide where to catch it and what to do once the condition is caught. This must be done strictly according to the actual needs of the application, not based on a compiler alert. All other errors must be allowed to freely propagate to the topmost handler where they would be logged and a graceful (perhaps, termination) action will be taken.

And the main thought or article is:

When it comes to error handling in software, the only safe and correct assumption that may ever be made is that a failure may occur in absolutely every subroutine or module that exists!

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.

查看更多
一个人的天荒地老
4楼-- · 2018-12-31 23:37

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:

  1. Catch and handle a specific exception. This is to implement retry logic, for example.
  2. Catch and rethrow other exceptions. All that happens here is usually logging, and its usually a trite message like "Unable to open $filename". These are errors you can't do anything about; only a higher levels knows enough to handle it.
  3. Catch everything and display an error message. This is usually at the very root of a dispatcher, and all it does it make sure it can communicate the error to the caller via a non-Exception mechanism (popup dialogue, marshaling an RPC Error object, etc).
查看更多
孤独寂梦人
5楼-- · 2018-12-31 23:37

Anders speaks about the pitfalls of checked exceptions and why he left them out of C# in episode 97 of Software Engineering radio.

查看更多
素衣白纱
6楼-- · 2018-12-31 23:39

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() {

try {
     ... do something ...
} catch (Throwable throwable) {
     ApplicationContext.getExceptionService().handleException("Handle this exception", throwable);
}

}

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... :)

查看更多
无色无味的生活
7楼-- · 2018-12-31 23:40

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.

查看更多
登录 后发表回答