last day (15 days later) » 

19:53
302
A: The case against checked exceptions

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

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: 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: +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.
This is a very strong argument (and I agree with it in general), but there is a case where it doesn't work: generic callbacks. If I have some a library calls some user-defined code, there is no way (that I know of, in java) for that library to propagate checked exceptions from the user-code that it calls to the user code that calls it. This problem also extends to other parts of the type system of many statically typed languages that do not support proper generic types. This answer would be improved by a mention of this (and perhaps a response).
Thanks for the detailed response. I do agree with most of this, however, I don't believe 'ubiquity' or 'informing the user' are valid factors. The first point, when the error is out of the API programmer's control and out of the API client's control, is all that is needed to validate the use of a checked exception. The most obvious misuse of checked exceptions I have encountered is the API for org.json.JSONObject. When working with pre-validated JSON content it is correct to write 'try, da da da da da, catch, curly curly', otherwise I would be writing dead code in the catch clause.
19:53
@JamesWald: I would posit that the proper behavior with regard to checked exceptions a method is never supposed to throw would be to wrap them in some kind of run-time error; indeed, I would further posit that 99% of the griping about checked exceptions stems from the lack of a concise way to express that declaratively rather than imperatively.
@supercat Since I last wrote this I've learned to wrap and throw using runtime exceptions (or assertion errors where appropriate).
@JamesWald: Do you agree that it would have been nice if there had been a way of wrapping a block in a declaration "doesntcatch FooException,BarException", and having the compiler automatically perform the appropriate catch-wrap-rethrow?
@supercat I think Java 7's syntax for multi-catch exceptions is a good compromise. It looks very much like existing try-catch blocks and it doesn't require new bytecode so it's also backwards compatible. I'm using it for Android development today even though devices prior to Android 4.4 KitKat don't support Java 7's new bytecode for try-with-resources.
@JamesWald: A doesntcatch directive wouldn't require new byte code, and I would think it better conveyed a programmer's intention than would catch-and-rethrow, catch-and-swallow, or--worse--throws. A method should only allow checked exceptions to percolate out if it knows what they mean, and knows the disruption of program flow won't cause other things to be broken. If a method calls another which isn't expected to actually throw a checked exception but it does anyway, percolating out that exception may cause a caller to erroneously believe it can handle the condition that caused it.
Wrong @Rhubarb. Checked exceptions were intended for 'contingencies' which could & should be handled, but were always incompatible with "throw early, catch late" best practice. Opening a file is a cherry-picked example, which can be handled. Most IOException (eg writing a byte), SQLException, RemoteException are impossible to handle in a meaningful way. Failure or retry should be at "business" or "request" level, and checked exceptions -- as used in Java libraries -- are a mistake that makes that difficult. literatejava.com/exceptions/…
19:53
There is some irony that the only expert opinion you defer to - the Bruce Eckel/Anders interview - disagrees with your position. In the interview, BOTH Bruce and Anders agree Checked Exceptions was a serious mistake in Java, Anders feeling good he dodged it in C#, and Bruce regretting it in Java.
I think this whole answer focuses very little on OP's question of the case against checked exceptions.
I think this answer fundamentally misses the point that where the exception is thrown is very rarely close to the place you want to handle it. As a result, if you have database calls deep in your hierarchy throwing SQLException, you're forced to pollute nearly every function in your web app with throws SQLException, just so your global handler can catch it and return 500. Such mindless repetition offers no benefit whatsoever. throws declarations become meaningless noise that you must train yourself to ignore, and if you do so, you're not getting the supposed benefit.
@Rhubarb I don't see why you believe it's essential that I check FileNotFound, but not that I also check "DriveBusy", "OutOfHandles", "InsufficientPermission" and countless hundreds of other specific error cases which all amount to "You can't open that file"
@jpmc26 You're not forced to pollute anything with SQLException throws, doing so means you're not handling checked exceptions correctly. Throws clauses are part of the interface and putting implementation details in it is bad design. Whatever code is getting the SQLExceptions should, if it cannot usefully handle them, catch them and throw some other exception that conveys what that error means in terms of the domain of that function (perhaps after logging the details of this exception for debugging), or throw an unchecked exception if more appropriate.
@EricS The correct way to handle an unexpected SQLException during a web request is to let it bubble up to the global handler and cause a 500 error; no other useful action can be taken. Such global handlers are usually part of or registered with the web framework that calls out to your code. Even if you were correct, a bunch of try/catch/throw sets is even more boiler plate/pollution/repitition than a throws declaration and has the even worse additional downside of hiding the real error, making it more difficult to understand the cause of the error.
19:53
@jpmc26 Keeping the separation between interface and implementation clean is far more important. If there is going to be any mess it should be contained in the implementation code not leaked into the interface (i.e. throws). Your web framework ought to be able to Runtime exception you would likely want to wrap the SQLException in if it was not appropriate to handle in your code.
@EricS Wrapping something in an unchecked exception does nothing to separate the implementation from the interface. The callers still have to be prepared for exceptions to be thrown. Every line of code you write should be written under the assumption that something it calls will one day throw an exception you didn't anticipate, so it should make a best effort not to leave anything in a wrong state when that happens. Whether or not the function declaration has a throws on it or not solves no practical problems, and what you advocate makes developers less productive for no benefit.
@jpmc26 You seem to me missing the point of unchecked exceptions. Your function already can potentially throw an unchecked exception, so yes, something, at some level should handle that, and should be handling it already, so wrapping a SQLException that your function can not do anything useful with in a RuntimeException adds no additional overhead. But making your function throw SQLException has large impact and pollutes the interface. You also may not have control over the interface you are implementing and making it throw SQLException may not even be an option.
@EricS I'm not missing the point. I'm saying checked exceptions have no value, and all the stuff around them is useless boilerplate that doesn't actually improve productivity or quality even slightly. It doesn't actually solve any problems, including the one it promises to: forcing developers to handle them. The fact that you're suggesting eschewing checked exceptions by wrapping them with unchecked ones only strengthens my argument.
That's not what I'm suggesting. Checked exceptions are useful, they force the programmer to decide how to handle them in the code using the functions that throw them (but that is a different point than what we've been arguing about). Deciding that the code cannot handle them usefully and "translating" them to an unchecked exception is one of several possibilities to choose from.
19:53
The main problem with this answer is that it totally misrepresents Hejlsberg's actual argument against checked exceptions - the fact that it encourages bad practices is only one of the arguments, and not the most compelling if you ask me. A more accurate tl;dr would actually be the interface pollution aspect, especially in the face of future changes that might introduce new kinds of checked exceptions - then you're really in a bind, because that's a breaking change to all your callers. it is this fundamental problem that begets the bad practices

last day (15 days later) »