tags:

views:

2711

answers:

19

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 blog, 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.

+8  A: 

I initially agreed with you, as I've always been in favour of checked exceptions, and began to think about why I don't like not having checked exceptions in .Net. But then I realised that I don't infact like checked exceptions.

To answer you question, yes, I like my programs to show stack traces, preferably really ugly ones. I want the application to explode into a horrible heap of the ugliest error messages you could ever want to see.

And the reason is because, if it does that, I have to fix it, and I have to fix it right away. I want to know immediately that there is a problem.

How many times do you actually handle exceptions? I'm not talking about catching exceptions -- I'm talking about handling them? It's too easy to write the following:

try {
  thirdPartyMethod();
} catch(TPException e) {
  // this should never happen
}

And I know you can say that it's bad practice, and that 'the answer' is to do something with the exception (let me guess, log it?), but in the Real World (tm), most programmers just don't do it.

So yes, I don't want to catch exceptions if I don't have to do so, and I want my program to blow up spectacularly when I screw up. Silently failing is the worst possible outcome.

Travis
Java encourages you to do this sort of thing, so that you don't have to add every type of exception to every method signature.
Justice
I handle the exception, with code inside of the catch 100% of the time. The code is more than simply logging the fact that the exception is not too often. Most often the code is throwing a different exception type.
TofuBeer
Funny.. ever since I embraced checked exceptions correctly and used them appropriately my programs stopped blowing up in huge steaming pile of in your face customer dissatisfaction. If while developing you have big ugly bad stack trace then the customer is bound to get them as well. D'love to see his face when he sees ArrayIndexOutOfBoundsException with a mile high stack trace on his crashed system instead of a little tray notification saying that the color config for button XYZ could not be parsed so the default was used instead with the software happily humming along
Newtopian
A: 

Here's one argument against checked exceptions.

finnw
+1 You might want to summarize the argument in your answer though? They are like invisible gotos and early exits for your routines, scattered throughout the program.
MarkJ
That's more an argument against Exceptions in general.
Ionuț G. Stan
have you actually read the article !! Firstly he talks about exceptions in general, secondly the section "They are invisible in the source code" applies specifically to UNCHECKED exception. This is the whole point of checked exception... so that you KNOW what code throws what where
Newtopian
+4  A: 

I have been working with several developers in the last three years in relatively complex applications. We have a code base that uses Checked Exceptions quite often with proper error handling, and some other that doesn't.

So far, I have it found easier to work with the code base with Checked Exceptions. When I am using someone else's API, it is nice that I can see exactly what kind of error conditions I can expect when I call the code and handle them properly, either by logging, displaying or ignoring (Yes, there is valid cases for ignoring exceptions, such as a ClassLoader implementation). That gives the code I am writing an opportunity to recover. All runtime exceptions I propagate up until they are cached and handled with some generic error handling code. When I find a checked exception that I don't really want to handle at a specific level, or that I consider a programming logic error, then I wrap it into a RuntimeException and let it bubble up. Never, ever swallow an exception without a good reason (and good reasons for doing this are rather scarce)

When I work with the codebase that does not have checked exceptions, it makes it to me a little bit harder to know before hand what can I expect when calling the function, which can break some stuff terribly.

This is all of course a matter of preference and developer skill. Both ways of programming and error handling can be equally effective (or noneffective), so I wouldn't say that there is The One Way.

All in all, I find it easier to work with Checked Exceptions, specially in large projects with lot of developers.

Mario Ortegón
I do to. For me they are an essential part of a contract. Without having to get to detailed in the API documentation, I can quickly know the likeliest of error scenarios.
Wayne Hartman
+20  A: 

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).
Richard Levasseur
You could have made specific subclasses of AppSpecificException to allow separation while keeping the plain method signatures.
Thorbjørn Ravn Andersen
Also a very important addition to item 2, is that it allows you to ADD INFORMATION to the exception caught (e.g. by nesting in a RuntimeException). It is much, much better to have the name of the file not found in the stack trace, than hidden deep down in a log file.
Thorbjørn Ravn Andersen
Basically your argument is "Managing exceptions is tiring so I'd rather not deal with it". As the exception bubbles up it looses meaning and context making is practically useless. As designer of an API you should make is contractually clear as to what can be expected when things go wrong, if my program crashes because I was not informed that this or that exception can "bubbles up" then you, as designer, failed and as a result of your failure my system is not as stable as it can be.
Newtopian
Thats not what I'm saying at all. Your last sentence actually agrees with me. If everything is wrapped in AppSpecificException, then it doesn't bubble up (and meaning/context is lost), and, yes, the API client is not being informed - this is exactly what happens with checked exceptions (as they are in java), because people don't want to deal with functions with lots of `throws` declarations.
Richard Levasseur
A: 

I think that this is an excellent question and not at all argumentative. I think that 3rd party libraries should (in general) throw unchecked exceptions. This means that you can isolate your dependencies on the library (i.e. you don't have to either re-throw their exceptions or throw Exception - usually bad practice). Spring's DAO layer is an excellent example of this.

On the other hand, exceptions from the core Java API should in general be checked if they could ever be handled. Take FileNotFoundException or (my favourite) InterruptedException. These conditions should almost always be handled specifically (i.e. your reaction to an InterruptedException is not the same as your reaction to an IllegalArgumentException). The fact that your exceptions are checked forces developers to think about whether a condition is handle-able or not. (That said, I've rarely seen InterruptedException handled properly!)

One more thing - a RuntimeException is not always "where a developer got something wrong". An illegal argument exception is thrown when you try and create an enum using valueOf and there's no enum of that name. This is not necessarily a mistake by the developer!

oxbow_lakes
+3  A: 

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

Chuck Conway
+15  A: 

Artima published an interview with one of the architects of .NET, Anders Hejlsberg, which acutely covers the arguments against checked exceptions. A short taster:

The throws clause, at least the way it's implemented in Java, doesn't necessarily force you to handle the exceptions, but if you don't handle them, it forces you to acknowledge precisely which exceptions might pass through. It requires you to either catch declared exceptions or put them in your own throws clause. To work around this requirement, people do ridiculous things. For example, they decorate every method with, "throws Exception." That just completely defeats the feature, and you just made the programmer write more gobbledy gunk. That doesn't help anybody.

Le Dude
In fact, the chief architect.
Trap
I have read that, to me his argument boils down to "there are bad programmers out there".
TofuBeer
TofuBeer, not at all. The whole point is that many times you don't know what to do with the Exception that the called method throws, and the case you're really interested in isn't even mentioned. You open a file, you get an IO Exception, for instance... that's not my problem, so I throw it up. But the top-level calling method will just want to stop processing and inform the user that there's an unknown problem. The checked Exception didn't help at all. It was one of a million strange things that can happen.
Yar
@yar, if you don't like the checked exception, then do a "throw new RuntimeException("we did not expect this when doing Foo.bar()", e)" and be done with it.
Thorbjørn Ravn Andersen
TofuBeer, I think his real argument is that there are humans out there. And that on the whole, it's not convincing that the pain incurred using checked exceptions is less than the pain incurred without them.
Phil
+12  A: 

In short:

Exceptions are an API design question. -- No more, no less.

The argument for checked exceptions:

To understand why checked exceptions might not be good thing, let's turn the question around and ask: When or why are checked exceptions attractive, i.e. why would you want the compiler to enforce declaration of exceptions?

The answer is obvious: Sometimes you need to catch an exception, and that is only possible if the code being called offers a specific exception class for the error that you are interested in.

Hence, the argument for checked exceptions is that the compiler forces programmers to declare which exceptions are thrown, and hopefully the programmer will then also document specific exception classes and the errors that cause them.

In reality though, ever too often a package com.acme only throws an AcmeException rather than specific subclasses. Callers then need to handle, declare, or re-signal AcmeExceptions, but still cannot be certain whether an AcmeFileNotFoundError happened or an AcmePermissionDeniedError.

So if you're only interested in an AcmeFileNotFoundError, the solution is to file a feature request with the ACME programmers and tell them to implement, declare, and document that subclass of AcmeException.

So why bother?

Hence, even with checked exceptions, the compiler cannot force programmers to throw useful exceptions. It is still just a question of the API's quality.

As a result, languages without checked exceptions usually do not fare much worse. Programmers might be tempted to throw unspecific instances of a general Error class rather than an AcmeException, but if they care at all about their API quality, they will learn to introduce an AcmeFileNotFoundError after all.

Overall, the specification and documentation of exceptions is not much different from the specification and documentation of, say, ordinary methods. Those, too, are an API design question, and if a programmer forgot to implement or export a useful feature, the API needs to be improved so that you can work with it usefully.

If you follow this line of reasoning, it should be obvious that the "hassle" of declaring, catching, and re-throwing of exceptions that is so common in languages like Java often adds little value.

It is also worth noting that the Java VM does not have checked exceptions -- only the Java compiler checks them, and class files with changed exception declarations are compatible at run time. Java VM security is not improved by checked exceptions, only coding style.

David Lichteblau
+28  A: 

The thing about checked exceptions is that they are not really exceptions by the usual understanding of the concept. Instead, they are API alternative return values.

The whole idea of exceptions is that an error thrown somewhere way down the call chain can bubble up and be handled by code somewhere further up, without the intervening code having to worry about it. Checked exceptions, on the other hand, require every level of code between the thrower and the catcher to declare they know about all forms of exception that can go through them. This is really little different in practice to if checked exceptions were simply special return values which the caller had to check for. eg.[pseudocode]:

public [int or IOException] writeToStream(OutputStream stream) {
    [void or IOException] a= stream.write(mybytes);
    if (a instanceof IOException)
        return a;
    return mybytes.length;
}

Since Java can't do alternative return values, or simple inline tuples as return values, checked exceptions are are a reasonable response.

The problem is that a lot of code, including great swathes of the standard library, misuse checked exceptions for real exceptional conditions that you might very well want to catch several levels up. Why is IOException not a RuntimeException? In every other language I can let an IO exception happen, and if I do nothing to handle it, my application will stop and I'll get a handy stack trace to look at. This is the best thing that can happen.

Maybe two methods up from the example you want to catch all IOExceptions from the whole writing-to-stream process, abort the process and jump into the error reporting code; in Java you can't do that without adding ‘throws IOException’ at every call level, even levels that themselves do no IO. Such methods should not need to know about the exception handling; having to add exceptions to their signatures:

  1. unnecessarily increases coupling;
  2. makes interface signatures very brittle to change;
  3. makes the code less readable;
  4. is so annoying that it the common programmer reaction is to defeat the system by doing something horrible like ‘throws Exception’, ‘catch (Exception e) {}’, or wrapping everything in a RuntimeException (which makes debugging harder).

And then there's plenty of just ridiculous library exceptions like:

try {
    httpconn.setRequestMethod("POST");
} catch (ProtocolException e) {
    throw CanNeverHappenException("oh dear!");
}

When you have to clutter up your code with ludicrous crud like this, it is no wonder checked exceptions receive a bunch of hate, even though really this is just simple poor API design.

Another particular bad effect is on Inversion of Control, where component A supplies a callback to generic component B. Component A wants to be able to let an exception throw from its callback back to the place where it called component B, but it can't because that would change the callback interface which is fixed by B. A can only do it by wrapping the real exception in a RuntimeException, which is yet more exception-handling boilerplate to write.

Checked exceptions as implemented in Java and its standard library mean boilerplate, boilerplate, boilerplate. In an already verbose language this is not a win.

bobince
In your code example, it would be best to chain the exceptions so that the original cause can be found when reading the logs: throw CanNeverHappenException(e);
Esko Luontola
+18  A: 

Rather than rehash all the (many) reasons against checked exceptions, I'll pick just one. I've lost count of the number of times I've written this block of code:

try {
  // do stuff
} catch (AnnoyingcheckedException e) {
  throw new RuntimeException(e);
}

99% of the time I can't do anything about it. Finally blocks do any necessary cleanup (or at least they should).

I've also lost count of the number of times I've seen this:

try {
  // do stuff
} catch (AnnoyingCheckedException e) {
  // do nothing
}

Why? Because someone had to deal with it and was lazy. Was it wrong? Sure. Does it happen? Absolutely. What if this were an unchecked exception instead? The app would've just died (which is preferable to swallowing an exception).

And then we have infuriating code that uses exceptions as a form of flow control, like java.text.Format does. Bzzzt. Wrong. A user putting "abc" into a number field on a form is not an exception.

Ok, i guess that was three reasons.

cletus
+34  A: 

I think I read the same Bruce Eckel interview that you did - and it's always bugged me. In fact, the argument was made by the interviewee (if this is indeed the post you're talking about) Anders Hejlsberg, the MS genius behind .Net and C#.

http://www.artima.com/intv/handcuffs.html

Fan though I am of Hejlsberg and his work, this argument has always struck me as bogus. It basically boils down to:

"Checked exceptions are bad because programmers just abuse them by always catching them and dismissing them which leads to problems being hidden and ignored that would otherwise be presented to the user".

By "otherwise presented to the user" I mean if you use a runtime exception the lazy programmer will just ignore it (versus catching it with an empty catch block) and the user will see it.

The summary of the summary of the argument is that "Programmers wont use them properly and not using them properly is worse than not having them".

There is some truth to this argument and in fact I suspect Goslings motivation for not putting operator overrides in Java comes from a similar argument - they confuse the programmer because they are often abused.

But in the end I find it a bogus argument of Hejlsbergs and possibly a post-hoc one created to explain the lack rather than a well thought out decision.

I would argue that while the over-use of checked exceptions is a bad thing and tends to lead to sloppy handling by users, but the proper use of them allows the API programmer to give great benefit to the API client programmer.

Now the API programmer has to be careful not to throw checked exceptions all over the place, or they will simply annoy the client programmer. The very lazy client programmer will resort to catch (Exception) {} as Hejlsberg warns and all benefit will be lost and hell will ensue. But in some circumstances there's just no substitute for a good checked exception.

For me the classic example is the file-open API. Every programming language in the history of languages (on file systems at least) has an API somewhere that lets you open a file. And every client programmer using this API knows that they have to deal with the case that the file they are trying to open doesn't exist. Let me rephrase that: Every client programmer using this API should know that they have to deal with this case. And there's the rub: can the API progammer help them know they should deal with it through commenting alone or can they indeed insist the client deal with it.

In C the idiom goes something like

  if (f = fopen("goodluckfindingthisfile")) { ... } 
  else { // file not found ...

where fopen indicates failure by returning 0 and C (foolishly) lets you treat 0 as a boolean and... Basically you learn this idiom and you're okay. But what if you're a noob and you didn't learn the idiom. Then of course you start out with

   f = fopen("goodluckfindingthisfile");
   f.read(); // BANG! 

and learn the hard way.

Note that we're only talking about strongly typed languages here: There's a clear idea of what an API is in a strongly typed language: It's a smorgasbord of functionality (methods) for you to use with a clearly defined protocol for each one.

That clearly defined protocol is typically defined by a method signature. Here fopen requires that you pass it a string (or a char* in the case of C). If you give it something else you get a compile-time error. You didn't follow the protocol - you're not using the API properly.

In some (obscure) languages the return type is part of the protocol too. If you try to call the equivalent of fopen() in some languages without assigning it to a variable you'll also get a compile time error (you can only do that with void functions).

The point I'm trying to make is that: In a strongly typed language the API programmer encourages the client to use the API properly by preventing their client code from compiling if it makes any obvious mistakes.

(In a dynamically typed language, like Ruby, you can pass anything, say a float, as the file name - and it will compile. Why hassle the user with checked exceptions if you're not even going to control the method arguments. The arguments made here apply to stronly-typed langauges only)

So, what about checked exceptions?

Well here's one of the Java APIs you can use for opening a file.

try {
  f = new FileInputStream("goodluckfindingthisfile");
}
catch (FileNotFoundException e) {
  // deal with it. No really, deal with it!
  ... // this is me dealing with it
}

See that catch? Here's the signature for that API method:

public FileInputStream(String name)
                throws FileNotFoundException

Note that FileNotFoundException is a checked exception.

The API programmer is saying this to you: "You may use this constructor to create a new FileInputStream but you

a) must pass in the file name as a String
b) must accept the possibility that the file might not be found at runtime"

And that's the whole point as far as I'm concerned.

The key is basically what the question states as "Things that are out of the programmers control" My first thought was that he/she means things that are out of the API programmers control. But in fact, checked exceptions when used properly should really be for things that are out of both the client programmer's and the API programmer's control. I think this is the key to not abusing checked exceptions.

I think the file-open illustrates the point nicely. The API programmer knows you might give them a file name that turns out to be nonexistent at the time the API is called, and that they won't be able to return you what you wanted, but will have to throw an exception. They also know that this will happen pretty regularly and that the client programmer might expect the file name to be correct at the time they wrote the call, but it might be wrong at runtime for reasons beyond their control too.

So the API makes it explicit: There will be cases where this file doesn't exist at the time you call me and you had damn well better deal with it.

This would be clearer with a counter-case. Imagine I'm writing a table API. I have table model somewhere with an API with this method:

   public RowData getRowData(int row) 

Now as an API programmer I know there will be cases where some client passes in a negative value for the row or a row value outside of the table. So I might be tempted to throw a checked exception and force the client to deal with it:

public RowData getRowData(int row) throws CheckedInvalidRowNumberException

(I wouldn't really call it "Checked" of course).

This is bad use of checked exceptions. The client code is going to be full of calls to fetch row data, every one of which is going to have to use a try/catch, and for what? Are they going to report to the user that the wrong row was sought? Probably not - because whatever the UI surrounding my table view is, it shouldn't let the user get into a state where an illegal row is being requested. So it's a bug on the part of the client programmer.

The API programmer can still predict that the client will code such bugs and should handle it with a runtime exception like an IllegalArgumentException.

With a checked exception in getRowData, this is clearly a case that's going to lead to Hejlsbergs lazy programmer simply adding empty catches. When that happens, the illegal row values will not be obvious even to the tester or the client developer debugging, rather they'll lead to knock-on errors that are hard to pinpoint the source of. Arianne rockets will blow up after launch.

Okay, so here's the problem: I'm saying that the checked exception FileNotFoundException is not just a good thing but an essential tool in the API programmers toolbox for defining the API in the most useful way for the client programmer. But the CheckedInvalidRowNumberException is a big inconvenience, leading to bad programming and should be avoided. But how to tell the difference.

I guess it's not an exact science and I guess that underlies and perhaps justifies to a certain extent Hejlsbergs argument. But I'm not happy throwing the baby out with the bathwater here, so allow me to extract some rules here to distinguish good checked exceptions from bad:

  1. Out of clients control or Closed vs Open:

    Checked exceptions should only be used where the error case is out of control of both the API and the client programmer. This has to do with how open or closed the system is. In a constrained UI where the client programmer has control, say, over all of the buttons, keyboard commands etc that add and delete rows from the table view, (a closed system) it is a client programming bug if it attempts to fetch data from a nonexistent row. In a file based operating system where any number of users/applications can add and delete files (an open system) it is conceivable that the file the client is requesting has been deleted without their knowledge so they should be expected to deal with it.

  2. Ubiquity:

    Checked exceptions should not be used on an API call that is made frequently by the client. By frequently I mean from a lot of places in the client code - not frequently in time. So a client code doesn't tend to try to open the same file a lot, but my table view gets RowData all over the place from different methods. In particular I'm going to be writing a lot of code like

    if (model.getRowData().getCell(0).isEmpty())

    and it will be painful to have to wrap in try/catch every time.

  3. Informing the User:

    Checked exceptions should be used in cases where you can imagine a useful error message being presented to the end user. This is the "and what will you when it happens?" question I raise above. It also relates to item 1. Since you can predict that something outside of your client-API system might cause the file to not be there, you can reasonably tell the user about it:

    "Error: could not find the file 'goodluckfindingthisfile'"

    Since your illegal row number was caused by an internal bug and through no fault of the user, there's really no useful information you can give them. If your app doesn't let runtime exceptions fall through to the console it will probably end up giving them some ugly message like:

    "Internal error occured: IllegalArgumentException in ...."

    In short, if you don't think your client programmer can explain your exception in a way that helps the user, then you should probably not be using a checked exception.

So those are my rules. Somewhat contrived, and there will doubtless be exceptions (please help me refine them if you will). But my main argument is that there are cases like FileNotFoundException where the checked exception is as important and useful a part of the API contract as the parameter types. So we should not dispense with it just because it is misused.

Sorry, didn't mean to make this so long and waffly. Let me finish with two suggestions:

A: API programmers: use checked exceptions sparingly to preserve their usefulness. When in doubt use an unchecked exception.

B: Client programmers: get in the habit of creating a wrapped exception (google it) early on in your development. Jdk 1.4 and later provide a constructor in RuntimeException for this, but you can easily create your own too. Here's the constuctor:

public RuntimeException(Throwable cause)

Then get in the habit of whenever you have to handle a checked exception and you're feeling lazy (or you think the API programmer was overzealous in using the checked exception in the first place), don't just swallow the exception, wrap it and rethrow it.

try {
  overzealousAPI(thisArgumentWontWork);
}
catch (OverzealousCheckedException exception) {
  throw new RuntimeException(exception);  
}

Put this in one of your IDE's little code templates and use it when you're feeling lazy. This way if you really need to handle the checked exception you'll be forced to come back and deal with it after seeing the problem at runtime. Because, believe me (and Anders Hejlsberg) you're never going to come back to that TODO in your

catch (Exception e) { /* TODO deal with this at some point (yeah right) */}
Rhubarb
Long, but interesting... +1
Mario Ortegón
Opening files is actually a good example for utterly counterproductive checked exceptions are. Because most of the time the code that opens the file can NOT do anything useful about the exception - that's better done several layers up the call stack. The checked exception forces you to clutter your method signatures just so you can do what you would have done anyway - handle the exception in the place where it makes most sense to do so.
Michael Borgwardt
@Michael: Agreed you might generally handle these IO exceptions several levels higher - but I don't hear you denying that as an API client you _have_ to anticipate these. For this reason, I think checked exceptions are appropriate.Yeah, you are going to have to declared "throws" on each method up call stack, but I disagree that this is clutter. It's useful declarative information in your method signatures. You're saying: my low-level methods might run into a missing file, but they'll leave the handling of it to you. I see nothing to lose and only good, clean code to gain
Rhubarb
@Rhubarb: +1, very interesting answer, shows arguments for both sides. Great.About your last comment: note that declaring throws on each method up the call stack may not always be possible, especially if you are implementing an interface along the way.
Martinho Fernandes
+1 Amen brother. Checked exceptions are just another tool for API design. It's not Java's fault that stupid programmers don't want to use them the way they were designed. If you want to open a file, you HAVE to anticipate the fact that the file may not be found. That's just the nature of filesystems.
mcjabberz
+1  A: 

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.

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.

Kurt Schelfthout
+6  A: 

The article Effective Java Exceptions explains nicely when to use unchecked and when to use checked exceptions. Here are some quotes from that article to highlight the main points:

Contingency: An expected condition demanding an alternative response from a method that can be expressed in terms of the method's intended purpose. The caller of the method expects these kinds of conditions and has a strategy for coping with them.

Fault: An unplanned condition that prevents a method from achieving its intended purpose that cannot be described without reference to the method's internal implementation.

(SO doesn't allow tables, so you might want to read the following from the original page...)

Contingency

  • Is considered to be: A part of the design
  • Is expected to happen: Regularly but rarely
  • Who cares about it: The upstream code that invokes the method
  • Examples: Alternative return modes
  • Best Mapping: A checked exception

Fault

  • Is considered to be: A nasty surprise
  • Is expected to happen: Never
  • Who cares about it: The people who need to fix the problem
  • Examples: Programming bugs, hardware malfunctions, configuration mistakes, missing files, unavailable servers
  • Best Mapping: An unchecked exception
Esko Luontola
I know when to use them, I want to know why people who don't follow that advice... don't follow that advice :-)
TofuBeer
Because people is people?
Mario Ortegón
+1  A: 

A problem with checked exceptions is that exceptions are often attached to methods of an interface if even one implementation of that interface uses it.

Another problem with checked exceptions is that they tend to be misused. The perfect example of this is in java.sql.Connection's close() method. It can throw a SQLException, even though you've already explicitly stated that you're done with the Connection. What information could close() possibly convey that you'd care about?

Usually, when I close() a connection*, it looks something like this:

try {
    conn.close();
} catch (SQLException ex) {
    // Do nothing
}

Also, don't get me started on the various parse methods and NumberFormatException... .NET's TryParse, which doesn't throw exceptions, is so much easier to use it's painful to have to go back to Java (we use both Java and C# where I work).

*As an additional comment, a PooledConnection's Connection.close() doesn't even close a connection, but you still have to catch the SQLException due to it being a checked exception.

R. Bemrose
The mysql driver (for instance) can throw SQLException in close however...
TofuBeer
Right, any of the drivers can... the question is rather "why should the programmer care?" as he's done accessing the database anyway. The docs even warn you that you should always commit() or rollback() the current transaction before calling close().
R. Bemrose
Many people think that close on a file cannot throw an exception... http://stackoverflow.com/questions/588546/does-close-ever-throw-an-ioexception are you 100% certain that there are no cases that it would matter?
TofuBeer
I'm 100% certain that there are no cases that it *would* matter and that the caller *wouldn't* put in a try/catch.
Martin
+5  A: 

SNR

Firstly, checked exceptions increase the "signal-to-noise ratio" for the code. Anders Hejlsberg also talks about imperative vs declarative programming which is a similar concept. Anyway consider the following code snippets:

Update UI from non UI-thread in Java:

try  
{  
   // Run the update code on the Swing thread  
   SwingUtilities.invokeAndWait(new Runnable()  
   {  
       @Override  
       public void run()  
       {  
           try  
           {  
               // Update UI value from the file system data  
               FileUtility f = new FileUtility();  
               uiComponent.setValue(f.readSomething());  
           }  
           catch (IOException e)  
           {  
               throw new IllegalStateException("Error performing file operation.", e);  
           }  
       }  
   }  
}  
catch (InterruptedException ex)  
{  
   throw new IllegalStateException("Interrupted updating UI", ex);  
}  
catch (InvocationTargetException ex)  
{  
   throw new IllegalStateException("Invocation target exception updating UI", ex");  
}

Update UI from non UI-thread in C#:

private void UpdateValue()  
{  
   // Ensure the update happens on the UI thread  
   if (InvokeRequired)  
   {  
       Invoke(new MethodInvoker(UpdateValue));  
   }  
   else  
   {  
       // Update UI value from the file system data  
       FileUtility f = new FileUtility();  
       uiComponent.Value = f.ReadSomething();  
   }  
}

Which seems a lot clearer to me. When you start to do more and more UI work in Swing checked exceptions start to become really annoying and useless.

Jail Break

To implement even the most basic of implementations, such as Java's List interface, checked exceptions as a tool for design by contract fall down. Consider a list that is backed by a database or a filesystem or any other implementation that throws a checked exception. The only possible implementation is to catch the checked exception and rethrow it as an unchecked exception:

@Override
public void clear()  
{  
   try  
   {  
       backingImplementation.clear();  
   }  
   catch (CheckedBackingImplException ex)  
   {  
       throw new IllegalStateException("Error clearing underlying list.", ex);  
   }  
}

And now you have to ask what is the point of all that code? The checked exceptions just add noise, the exception has been caught but not handled and design by contract (in terms of checked exceptions) has broken down.

Conclusion

  • Catching exceptions is different to handling them.
  • Checked exceptions add noise to the code.
  • Exception handling works well in C# without them.

I blogged about this previously.

Luke Quinane
Update UI from non UI-thread in C#: - what if an exception occurs?
TofuBeer
In the example both Java and C# are just letting the exceptions propagate up without handling them (Java via IllegalStateException). The difference is that you may want to handle a FileNotFoundException but its unlikely that handling InvocationTargetException or InterruptedException will be useful.
Luke Quinane
And in the C# way how do I know that the I/O exception can occur? Also I would never throw an exception from run... I consider that abusing exception handling. Sorry but for that part of your code I just can see your side of it yet.
TofuBeer
The known exceptions are put into the C# "Javadoc"; good APIs will define all known exceptions this way.You may be able to catch a FileNotFound inside run() but some exceptions can't be handled there. Catching them inside run() but not properly handling isn't good. Perhaps I'm misunderstanding.
Luke Quinane
We are getting there :-) So with each new release of an API you have to comb through all your calls and look for any new exceptions that might happen? The can easily happen with internal to a company APIs since they don't have to worry about backwards compatibility.
TofuBeer
Did you mean *decrease* the signal-to-noise ratio?
Botond Balázs
A: 

As folks have already stated, checked exceptions don't exist in Java bytecode. They are simply a compiler mechanism, not unlike other syntax checks. I see checked exceptions a lot like I see the compiler complaining about unreachable code at b: if(true) { a; } b;. That's helpful but I might have done this on purpose, so let me ignore your warnings.

The fact of the matter is, you aren't going to be able to force every programmer to "do the right thing" if you enforce checked exceptions and everyone else is now collateral damage who just hates you for the rule you made.

Fix the bad programs out there! Don't try to fix the language to not allow them! For most folks, "doing something about an exception" is really just telling the user about it. I can tell the user about an unchecked exception just as well, so keep your checked exception classes out of my API.

Martin
A: 

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

adrian.tarau
+4  A: 

Ok... Checked exceptions are not ideal and have some caveat but they do serve a purpose. When creating an API there are specific cases of failures that are contractual of this API. When in the context of a strongly statically typed language such as Java if one does not use checked exceptions then one must rely on ad-hoc documentation and convention to convey the possibility of error. Doing so removes all benefit that the compiler can bring in handling error and you are left completely to the good will of programmers.

So, one removes Checked exception, such as was done in C#, how then can one programmatically and structurally convey the possibility of error ? How to inform the client code that such and such errors can occur and must be dealt with ?

I hear all sorts of horrors when dealing with checked exceptions, they are misused this is certain but so are unchecked exceptions. I say wait a few years when APIs are stacked many layers deep and you will be begging for the return of some kind of structured mean to convey failures.

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

Many have argued that not being able to load the file was almost always the end of the world for the process and it must die a horrible and painful death. So yeah.. sure ... ok.. you build an API for something and it loads file at some point... I as the user of said API can only respond... "Who the hell are you to decide when my program should crash !" Sure Given the choice where exceptions are gobbled up and leave no trace or the EletroFlabbingChunkFluxManifoldChuggingException with a stack trace deeper than the Marianna trench I would take the latter without a cinch of hesitation, but does this mean that it is the desirable way to deal with exception ? Can we not be somewhere in the middle, where the exception would be recast and wrapped each time it traversed into a new level of abstraction so that it actually means something ?

Lastly, most of the argument I see is "I don't want to deal with exceptions, many people do not want to deal with exceptions. Checked exceptions force me to deal with them thus I hate checked exception" To eliminate such mechanism altogether and relegate it to the chasm of goto hell is just silly and lacks jugement and vision.

If we eliminate checked exception we could also eliminate the return type for functions and always return a "anytype" variable... That would make life so much simpler now would it not ?

Newtopian
+1  A: 

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.

Joshua
You should have something like DAGNodeException in the interface, then catch the IOException and convert it to a DAGNodeException: public void call(DAGNode arg) throws DAGNodeException;
TofuBeer
@TofuBeer, that 's exactly my point. I find that constantly wrapping and unwrapping exceptions is worse than removing checked exceptions.
Joshua
Well we disagree completely then... but your article still does not answer the real underlying question of how you stop your application from displaying a stack trace to the user when a runtime exception is thrown.
TofuBeer