Don't throw, chuck!
http://james-iry.blogspot.com/2010/08/on-removing-java-checked-exceptions-by.html
Or simply use Scala... take your pick :)
>
> --
> You received this message because you are subscribed to the Google Groups "The Java Posse" group.
> To post to this group, send email to java...@googlegroups.com.
> To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
I never thought I'd see anything useful on an OSGi blog, but today I saw this:So if you accept that CheckedExceptions are a bad idea... read the comments on this post. There is a debate as to how to handle the atrocity that the CheckedException. There are two approaches that are debated:
1)void foo() {
try {
bar();
} catch( Exception e) {
throw new RuntimeException(e);
}
}
2)
void foo() throws Exception {
bar();
}I used to be in the #1 camp. But after reading the thread, I'm thinking that just putting throws Exception everywhere might be easier/more pragmatic. It's uglier, but it does make the stack dump more readable I think.
class ExceptionAdapter extends RuntimeException {
private final String stackTrace;
public Exception originalException;
public ExceptionAdapter(Exception e) {
super(e.toString());
originalException = e;
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
stackTrace = sw.toString();
}
public void printStackTrace() {
printStackTrace(System.err);
}
public void printStackTrace(java.io.PrintStream s) {
synchronized(s) {
s.print(getClass().getName() + ": ");
s.print(stackTrace);
}
}
public void printStackTrace(java.io.PrintWriter s) {
synchronized(s) {
s.print(getClass().getName() + ": ");
s.print(stackTrace);
}
}
public void rethrow() { throw originalException; }
} Thanks for the Lazy comment. You can handle Exceptions even if they are RuntimeExceptions
(just like you do in every language ever created other than Java). Usually you want to let them bubble up, so it's very annoying to have to deal with them at every level up the stack.
No one is arguing against ever handling exceptions.I'm reading Robert C. Martin's (Uncle Bob) "Clean Code" right now and I actually was surprised almost every code example he gives says "throws Exception".
But he does go on a rant against CheckedExceptions in the book so I guess he's just in the "throws Exception" camp as a solution to the problem.
I also just found this snippet for what Bruce Eckel advocates (from http://www.ibm.com/developerworks/library/j-jtp05254.html#resources):
--
Cédric
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
Has anyone ever done a robust api that is generally acknowledged as
nice that did include checked exceptions? Because... that is my gripe
with them. It isn't that they have a few bumps against them. It is
that I have never seen them done well.
Which is, I believe, why the Go folk have eschewed exceptions in favour
of return codes. They solve the problem C has with this by using
multiple return values -- which avoids having to find obscure out of
band information channels or usurping the domain to carve out an error
information channel.
value , errorCode = someOperationThatReturnsAValueAndAnErrorCode ( )
if ( errorIndicated ( errorCode ) ) {
processError ( errorCode )
} else {
processSuccess ( value )
}
Seems to be the idiomatic Go way of doing things. A return to a better
way or just backward looking?
--
Russel.
=============================================================================
Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel...@ekiga.net
41 Buckmaster Road m: +44 7770 465 077 xmpp: rus...@russel.org.uk
London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder
Checked or unchecked aside, one reason I like the separation between
the old C-style return value approach and exceptions is that an
exception is a clear statement that something very much out of the
ordinary has happened, something that the higher level business logic
is not expected to handle.
This clean separation has a cleansing effect on the code as well as
making it easier to look at unfamiliar code and separate business
logic from exception handling.
Personally I sit in the 'handle it immediately or wrap and throw'
camp. Not least because the most realistic place to handle the
exception is inside the method that it occurred. The further away from
the exception the handling code resides, the harder it becomes to code
a specific recovery action. So as a rule of thumb my classes will not
throw exceptions. If exceptions play an important part in the overall
component (for example in some kind of remote interface/adapter where
an exception will manifest if the thing on the other side is broken/
uncontactable) then this would be presented to the outside world as a
state change event (e.g. connection lost) rather than as an exception.
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
I've found that the typical "most realistic place to handle" an
exception is to take it all the way back to a user or developer
somehow. Otherwise, it probably wasn't that exceptional.
> (I'm not advocating that the blanket treatment of all checked exceptions as
> misguided is a good idea, but Cedric's already done a decent job of
> explaining this). With the lombok 0.10.0 beta, the dependency on Lombok at
> runtime will be eliminated via class file rewriting automatically.
> Otherwise, all you actually need at runtime is Lombok.class.
>
> I can't stress enough how important it is to manage your APIs properly.
I'll put to you the same challenge I put to Cedric. What is an API
that is generally liked and "uses checked exceptions correctly?" This
is a far cry from the immutable debate, where there are many good
examples. Same for operator overloading (one need only consider a
matrix library to see a good use for traditional operators on user
objects).
Neither of these strategies works well.The wrap-into-RuntimeException model means you're chasing down 'causes' EVERYWHERE - even runtimeexceptions are themselves wrapped in more runtimeexceptions. You can avoid some of this by catching RuntimeException separately and throwing them without wrapping, but you're still effectively eliminating the utility of stack traces.The "throws Exception" strategy cannot be combined when implementing any number of oft-implemented interfaces, such as Runnable.The proper solution if you really dislike checked exceptions is sneakythrows. James Iry's blogpost (as posted earlier, but here it is again, without expected and ridiculously annoying flippant "Use Scala" commentary by KevinBot): http://james-iry.blogspot.com/2010/08/on-removing-java-checked-exceptions-by.html
You can also use Lombok and either add @SneakyThrows or if thats too much magic for you, write this:try {.. do whatever} catch (Exception e) {throw Lombok.sneakyThrow(e);}which does NOT wrap exceptions but DOES eliminate all need to deal with them (I'm not advocating that the blanket treatment of all checked exceptions as misguided is a good idea, but Cedric's already done a decent job of explaining this). With the lombok 0.10.0 beta, the dependency on Lombok at runtime will be eliminated via class file rewriting automatically. Otherwise, all you actually need at runtime is Lombok.class.I can't stress enough how important it is to manage your APIs properly. Checked exceptions can be a good thing but most libraries I know (primary offender is java's runtime itself!) throw _WAY_ too many checked exceptions. IOException should have been unchecked, because there are many, many situations where you just can't do anything about it. Think of your consumers: If either (A) there are a significant number of situations where that exception is effectively not going to happen anyway, i.e. with InputStream.close(), don't make it checked. If (B) There are significant use cases where there's nothing useful to do for any part of a large chain, other than the very top (servlets, db failures, threads), don't make it checked.Also be consistent. IOException being checked and NumberFormatException being unchecked is ridiculous, it's the same situation, and arguably NFEx is easier to handle than IOException (you can ask a user to re-enter a number. It's kinda hard to ask a filesystem to try harder).
Finally, check your interfaces. Runnable's run should OF COURSE have included "throws Exception". Runnable's designed use is for threads, and Thread will (of course) handle any and all exceptions that leak through via the unhandledExceptionHandler. We're all jumping through hoops because of these brainfarts. Take more care when you write your own libraries.
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
On 24 Mar 2011 13:09, "Phil" <ph...@surfsoftconsulting.com> wrote:
>
> This is a discussion about Java exception handling, so any suggestion
> to avoid it by using another language can't really be viewed as
> anything but flippant... (whispers - or trolling)
>
"Java" is a platform, not just a language...
You often give the impression of critiquing Scala simply because it threatens your own library, and I'd hate to see someone with your technical achievements being ultimately judged as a fearmonger.
Which is, I believe, why the Go folk have eschewed exceptions in favour
of return codes. They solve the problem C has with this by using
multiple return values -- which avoids having to find obscure out of
band information channels or usurping the domain to carve out an error
information channel.
value , errorCode = someOperationThatReturnsAValueAndAnErrorCode ( )
if ( errorIndicated ( errorCode ) ) {
processError ( errorCode )
} else {
processSuccess ( value )
}
Seems to be the idiomatic Go way of doing things. A return to a better
way or just backward looking?
|
func WriteFile(filename string, data []byte, perm uint32) os.Error { |
|
f, err := os.Open(filename, os.O_WRONLY|os.O_CREAT|os.O_TRUNC, perm) |
|
if err != nil { |
|
return err |
|
} |
|
n, err := f.Write(data) |
|
f.Close() |
|
if err == nil && n < len(data) { |
|
err = io.ErrShortWrite |
| } |
--
Obviously, suggesting that Maybe/Option is a better solution is equally silly.
--
Cédric
error-via-return-value is far inferior to anything else as a complete solution to what checked/unchecked exceptions are trying to do. Here are the problems with it:(A) For any method that would ordinarily return void, this boils down to C-style "return error codes". I pray I don't have to explain why this is far far worse compared to exceptions (of either checked or unchecked variety).
(B) Where you can get away with returning maybes/options, you're making it much harder for code to decide to defer the handling of this error condition to something up the chain. It's also infectious - if as part of doing your thing you could run into errors, then you have to turn whatever you return into an Option/Maybe guard as well. At some point virtually every method returns option/maybe.
(C) You don't solve the problem of "where do we draw the line?" - when does an exception become sufficiently unlikely that you're better off making it a checked exception? The same question applies to: When do we return Option and when do we not? You're not solving any problems here.
Give me an example of a void method that has a checked exception that
isn't usually dealt with in the "wrap and throw" style.
> (B) Where you can get away with returning maybes/options, you're making it
> much harder for code to decide to defer the handling of this error condition
> to something up the chain. It's also infectious - if as part of doing your
> thing you could run into errors, then you have to turn whatever you return
> into an Option/Maybe guard as well. At some point virtually every method
> returns option/maybe.
How is it harder now? Especially when you usually have getOr methods
on the Option types. (That is, Option<A> typically has a getOr(A)
that will return what it holds or an alternative value. Couple this
with a getOrThrow(Exception) and you can easily decide right there
exactly what you will do if you didn't get the value. Or even better,
couple Either with some amazing abstractions out there and suddenly
the problem is much easier to reason about.)
Correct me if I'm wrong, I don't think any language (that has been
brought up) has completely done away with exceptions. Just checked
ones.
> (C) You don't solve the problem of "where do we draw the line?" - when does
> an exception become sufficiently unlikely that you're better off making it a
> checked exception? The same question applies to: When do we return Option
> and when do we not? You're not solving any problems here.
I'm still waiting for examples of some good usages of checked exceptions.
Regarding the issue of checked exceptions I'd say that all of bad things about them stems from IOException and SQLException.
(B) Where you can get away with returning maybes/options, you're making it much harder for code to decide to defer the handling of this error condition to something up the chain. It's also infectious - if as part of doing your thing you could run into errors, then you have to turn whatever you return into an Option/Maybe guard as well. At some point virtually every method returns option/maybe.Which is exactly what you want, sometimes, and is *exactly* what checked exceptions do.
Checked or unchecked aside, one reason I like the separation between
the old C-style return value approach and exceptions is that an
exception is a clear statement that something very much out of the
ordinary has happened, something that the higher level business logic
is not expected to handle.
This clean separation has a cleansing effect on the code as well as
making it easier to look at unfamiliar code and separate business
logic from exception handling.
Personally I sit in the 'handle it immediately or wrap and throw'
camp. Not least because the most realistic place to handle the
exception is inside the method that it occurred. The further away from
the exception the handling code resides, the harder it becomes to code
a specific recovery action. So as a rule of thumb my classes will not
throw exceptions. If exceptions play an important part in the overall
component (for example in some kind of remote interface/adapter where
an exception will manifest if the thing on the other side is broken/
uncontactable) then this would be presented to the outside world as a
state change event (e.g. connection lost) rather than as an exception.
There are plenty valid scenarios where exceptions should be caught and
handled, applying a blanket rule 'throw and forget' is almost as bad
as 'catch(Throwable t) {}' and indicates a weakness in the software
architecture.
On Mar 24, 7:57 am, Russel Winder <rus...@russel.org.uk> wrote:
> On Thu, 2011-03-24 at 00:34 +0000, Kevin Wright wrote:
> > It's quite simple... If there's something that can happen in your
> > method, and the caller *explicitly* needs to deal with it, then
> > there's a technique for dealing with that... It's commonly known as a
> > "return value". Yes, some form of "Maybe" or "Either" type combined
> > with lambdas makes this sort of thing a lot more concise and readable,
> > but it's certainly doable in Java, and the language isn't exactly a
> > stranger to boilerplate and verbosity!
>
> Which is, I believe, why the Go folk have eschewed exceptions in favour
> of return codes. They solve the problem C has with this by using
> multiple return values -- which avoids having to find obscure out of
> band information channels or usurping the domain to carve out an error
> information channel.
>
> value , errorCode = someOperationThatReturnsAValueAndAnErrorCode ( )
> if ( errorIndicated ( errorCode ) ) {
> processError ( errorCode )
> } else {
> processSuccess ( value )
> }
>
> Seems to be the idiomatic Go way of doing things. A return to a better
> way or just backward looking?
>
> --
> Russel.
> =============================================================================
> Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.win...@ekiga.net
> 41 Buckmaster Road m: +44 7770 465 077 xmpp: rus...@russel.org.uk
> signature.asc
> < 1KViewDownload
Cédric
2011/3/24 Cédric Beust ♔ <ced...@beust.com>:
> Absolutely. I think all the people who think that checked exceptions are a
> "failed experiment" or a "total failure" would probably think very
> differently if IOException and SQLException were runtime exceptions. In such
> a world, runtime exceptions would be much more frequent in Java code bases
> and, as a consequence, we would probably only see checked exceptions in
> places where they are really justified, thereby magnifying their usefulness.
Again, name a SINGLE checked exception that everyone agrees should be checked.
--
Cédric
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
I wasn't limiting the search scope to the java standard lib. Is there
an API that is generally regarded as having "great usage of checked
exceptions?"
--
Cédric
Again, name a SINGLE checked exception that everyone agrees should be checked.
FileNotFound.a) I neither want nor need a stacktrace (+ associated construction cost) in such a scenario
b) There may be a long chain of callers between where the exception is thrown and where it might reasonably be handled, if some of those intervening methods are generic and could also be used for other non-file operations then I certainly don't want to pollute their signatures.
Again, name a SINGLE checked exception that everyone agrees should be checked.
Use of exceptions is not usually something people rave about either way. Error handling is like doing dishes -- necessary, but hardly glamorous. Right now, people marvel at collections API, clever use of generics, annotations, whatever. But exceptions? People only complain about them, when they're inconveniently designed or just say nothing. I'm reluctant to say that any framework with checked exceptions in it, where people don't say anything about its exception API is a silent form of praise, but that's as good an answer as I can come up with off the cuff.
What? I can't think of a single well designed system involving checked
exceptions. Period. I can think of a few that use unchecked well.
And, having seen some slick uses of Either with Traversals, I've seen
some ridiculously well done error handling with those types. (The Box
type in lift is put to ridiculously nice usage in validating forms.)
Checked exceptions? I'm at a loss.
I'm not saying that just ditching checked exceptions makes for a
robust API. I'm saying I don't know of a single robust API with them.
I'll concede that the idea seems nice on paper. Still waiting to see
a good delivery, though.
On Thu, Mar 24, 2011 at 10:49 AM, Kevin Wright <kev.lee...@gmail.com> wrote:
Again, name a SINGLE checked exception that everyone agrees should be checked.
FileNotFound.a) I neither want nor need a stacktrace (+ associated construction cost) in such a scenarioYou are very unlikely to see one, unless you use a runtime exception, which you will most likely forget to handle.
b) There may be a long chain of callers between where the exception is thrown and where it might reasonably be handled, if some of those intervening methods are generic and could also be used for other non-file operations then I certainly don't want to pollute their signatures.There are patterns to avoid that. Exceptions that cross layer boundaries should be wrapped, although FileNotFoundException is probably an... er... exception to this rule. Either way, you want to handle that one and do something about it, and it's important enough that the compiler should make sure you don't forget to do it.
--
Cédric
> Having done a bit of C# development where exceptions are not checkedThe full story is that the designers of C# were not convinced that
> there were some times when I missed them.
they were worth the trouble.
--
Cédric
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
Could you elaborate on that, it goes against all documented interviews
I've come by over the years? Also, how could there be a backwards
compatibility issue on a new runtime and language?
FileNotFoundException, and isn't that great? Well, that's fine when you're just calling one API. The trouble begins when you start building big systems where you're talking to four or five different subsystems. Each subsystem throws four to ten exceptions. Now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. You end up having to declare 40 exceptions that you might throw. And once you aggregate that with another subsystem you've got 80 exceptions in your throws clause. It just balloons out of control."On Thursday, March 24, 2011 5:52:42 PM UTC+1, Josh Berry wrote:
On Thu, Mar 24, 2011 at 11:03 AM, Reinier Zwitserloot
<rein...@gmail.com> wrote:
> (A) For any method that would ordinarily return void, this boils down to
> C-style "return error codes". I pray I don't have to explain why this is far
> far worse compared to exceptions (of either checked or unchecked variety).Give me an example of a void method that has a checked exception that
isn't usually dealt with in the "wrap and throw" style.
How is it harder now? Especially when you usually have getOr methods
on the Option types. (That is, Option<A> typically has a getOr(A)
that will return what it holds or an alternative value. Couple this
with a getOrThrow(Exception) and you can easily decide right there
exactly what you will do if you didn't get the value. Or even better,
couple Either with some amazing abstractions out there and suddenly
the problem is much easier to reason about.)
I'm still waiting for examples of some good usages of checked exceptions.
On 25 Mar 2011 09:37, "Reinier Zwitserloot" <rein...@gmail.com> wrote:
>
> When we start arguing that a CPU/Memory only construct is "too slow", in regards to an I/O operation, you're grasping at some very tiny straws.
>
Admittedly not the best example :)
I'm just seeing this as part of a larger anti-pattern, where checked exceptions are used for non-exceptional return values and flow control, invoking the cost of building a stack trace in order to to so. I actually see this as an oxymoron, where the idea of a checked exception seems to be saying "here is a truly exceptional occurrence that you should expect on a regular basis"
It isn't exceptional for some given string not to specify the valid path to a file. If anything, given a bunch of random strings, it seems more surprising that one *would* be valid. So FileNotFound should be a normal and very plausible return value, not something treated as exceptional.
I asked for an example where you prefer checked because the exception
lets you know you can do something about it. I would think in those
examples, you'd typically just wrap all exceptions to a close or write
in some sort of "Fatal" and throw them up? Because, that is the most
likely scenario I've ever seen in those cases. Seriously, how much
effort are you going to make to close a file that is throwing an
exception? I'm more likely to have an error calling
Integer.parseInt than I am close on a file. Amusingly, one of those
is a runtime exception. :)
As for the "forgot to check error code," argument. That criticism
seems more aimed at c style returns where crap like getInt would
return a long. With Either types and proper usage of map/flatMap
(usually in a for comprehension), the errors are easy to propagate up
where they can be dealt with correctly.
> So you advocate both Either/Option *and* exceptions. Eh, that's piling on
> features for no clear added gain, if you ask me. Now we have to reason
As I said, I don't know a single proposal here that does not allow for
runtime exceptions. Even Haskel has them, if I'm not mistaken.
I agree that an API that is fully in the realm of Either/Option is
easier to reason about, but people do prefer writing in the realm of
exceptions, it seems.
> FileNotFound, FundsNotSufficientToCoverTransaction,
> InvocationTargetException, and yes, even IOException and SQLException. Some
> times. Other times the level i'm at is wholly inappropriate to treat these
> as checked exceptions so I'd like to opt out. If I can't have opt-out I'd
> rather they'd all just be unchecked.
I'm glad people were willing to answer the incredible softball. Now
answer the tough one. Give me an API that has "good use" of checked
exceptions. (As before, I'll let your choices above slide, even
though I know some folks disagree with them.)
I asked for an example where you prefer checked because the exception
lets you know you can do something about it.
I would think in those
examples, you'd typically just wrap all exceptions to a close or write
in some sort of "Fatal" and throw them up? Because, that is the most
likely scenario I've ever seen in those cases. Seriously, how much
effort are you going to make to close a file that is throwing an
exception?
I'm more likely to have an error calling
Integer.parseInt than I am close on a file. Amusingly, one of those
is a runtime exception. :)
As for the "forgot to check error code," argument. That criticism
seems more aimed at c style returns where crap like getInt would
return a long. With Either types and proper usage of map/flatMap
(usually in a for comprehension), the errors are easy to propagate up
where they can be dealt with correctly.
I agree that an API that is fully in the realm of Either/Option is
easier to reason about, but people do prefer writing in the realm of
exceptions, it seems.
I'm glad people were willing to answer the incredible softball. Now
answer the tough one. Give me an API that has "good use" of checked
exceptions. (As before, I'll let your choices above slide, even
though I know some folks disagree with them.)
Perhaps just perhaps the problem is that heirarchy is both a grouping mechanism and a way to define checkness. Therefore if a marker was applied to an exception to denote whether it (the exception) was checked or unchecked ignoring whether it extended exception/runtime etc perhaps things would be better and more flexible.More hyperbole perhaps including a Checked and Unchecked marker interfaces do the trick. The way to solve a child implementing Unchecked if a parent was Checked would be that the compiler would respect the most derived implements. Since Annotations were not around its perhaps the best solution for this mess.
Parent implements Checked // compiler treats Parent as checked.
Child implemented Unchecked // compiler treats Child as unchecked
You are a master at screwing with quote trees... I hadn't forgotten
what you hadn't mentioned yet. (I was referring there to where I
asked for void methods where you don't typically just rethrow or
log/ignore the exception.)
>> I'm more likely to have an error calling
>> Integer.parseInt than I am close on a file. Amusingly, one of those
>> is a runtime exception. :)
>
> As I already mentioned earlier in the thread. We are in vehement agreement
> regarding the consistency of checked vs. unchecked exceptions in java.
Right. My question is essentially this: You seem to be claiming that
people would like checked exceptions if they had been used well
somewhere. I'm asking for an example. I can't say it doesn't exist.
You are right that, if someone had a good API that used checked
exceptions, it could sway the popular opinion. You are also right
that most APIs that have them have some atrocious parts. My claim is
that I don't know of a good one. This "mythical well done checked
exception API" is a diversion that allows people to cling to the
thought that checked exceptions are a good idea.
> map/flatMap/Either/Option for OutputStream.close() would be very very
> stupid. If you forget to check, which I guarantee the majority will do, you
> silently eat I/O errors, which is extremely bad.
I think Haskel and a few other languages would like a word with you
for calling them stupid.
> So I'll just repeat the two arguments that you so conveniently decided to
> exclude in your retort. Don't ask me to list more examples again until
> you've discussed these two, please, or we'll go in circles all day:
>> FundsNotSufficientToCoverTransaction,
>> InvocationTargetException
I didn't exclude them in my retort, I've still got the context where I
began asking for APIs and eventually loosened it to just an exception.
Without the API around these two exceptions, it is impossible for me
to say that they should always be checked. In fact, just looking at
the name of the first, I can already say I prefer the monadic style
I've seen covered here to exceptions:
http://debasishg.blogspot.com/2010/09/domain-models-thinking-differently-in.html
You seem hellbent against that style, though.
My objection to checked exceptions is I suspect slightly different to
some.
In theory, they are a great idea. An extension to the static type
system (as such, its surprising that all exceptions in Scala aren't
checked!). The theory is that you write your code and force the user
of your API to actually think about the errors that might occur.
However, after 15 years, all the evidence is that this fails the
usability requirement. The mass of developers (right up to Sun) are
clearly unable to *use* this feature in a useful and meaningful way.
Thats all - the entire total of the argument for me.
Despite year after year of discussion, conference talks, forum
discussions, code reviews and much more, the Java community hasn't
managed to produce an agreed and successful use of the feature.
Examples in this case include all the catch and ignore, catch and
rethrow, adding of "Exception" to every single throws clause,
disagreement on how exception hierarchies should be structured,
arguments over whether a particular exception should be checked or
unchecked, and many more.
Thus, no matter how good a feature is in theory, how useful it might
be, how its "just a matter of training" or "using it properly", the
absence of successful usage and the presence of unsuccessful usage
tells you all you need to know - its a failure. Usability is the only
criteria that matters.
Stephen
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
On Fri, Mar 25, 2011 at 8:42 AM, Reinier Zwitserloot <rein...@gmail.com> wrote:
> On Friday, March 25, 2011 12:33:41 PM UTC+1, Josh Berry wrote:
>>
>> I asked for an example where you prefer checked because the exception
>> lets you know you can do something about it.
>
You are a master at screwing with quote trees... I hadn't forgotten
what you hadn't mentioned yet. (I was referring there to where I
asked for void methods where you don't typically just rethrow or
log/ignore the exception.)
I didn't exclude them in my retort, I've still got the context where I
began asking for APIs and eventually loosened it to just an exception.
Without the API around these two exceptions,
it is impossible for me
to say that they should always be checked. In fact, just looking at
the name of the first, I can already say I prefer the monadic style
I've seen covered here to exceptions:
http://debasishg.blogspot.com/2010/09/domain-models-thinking-differently-in.html
You seem hellbent against that style, though.
RemoteException // probably the most famous this should be unchecked exception
EOFException // checkness should be the same as IOException.
Perhaps just perhaps the problem is that heirarchy is both a grouping mechanism and a way to define checkness. Therefore if a marker was applied to an exception to denote whether it (the exception) was checked or unchecked ignoring whether it extended exception/runtime etc perhaps things would be better and more flexible.
With Either types and proper usage of map/flatMap(usually in a for comprehension), the errors are easy to propagate up
where they can be dealt with correctly.
On Fri, Mar 25, 2011 at 4:33 AM, Josh Berry <tae...@gmail.com> wrote:With Either types and proper usage of map/flatMap(usually in a for comprehension), the errors are easy to propagate up
where they can be dealt with correctly.Either types help with the "wrapping the information" aspect, which is undoubtedly superior to a HRESULT or encoding errors in variants ("ok, result = Foo()" that Go and Erlang seem to love so much).However, Either types do nothing for the propagation: you still end up having to 1) have all your methods return an Either type and 2) do the bubbling up yourself.
I want the language to take care of 2) for me and for 1), a `throws` signature is a much more sensitive place to identify the potential errors that can happen than the return type, which I'd like to save for my own usage.
--
Cédric
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
Apologies, I shouldn't have accused you of messing with the quote
tree. Odds are much more likely you just weren't considering the
subjects nearly as linearly as I was. (That is, the "topic" of this
part of my quote was specifically where I was asking for void methods
that throw exceptions that aren't typically treated as a runtime one.)
> InvocationTargetException is an exception in the standard runtime libraries.
> Invoking methods and constructors via reflection can cause this to be
> thrown. It indicates that the invocation worked just fine, but the thing you
> invoked threw an exception. While technically Method.invoke() does return
> something (Object, to be precise), if the author of the invoke call (thinks
> he) knows that the method doesn't return anything anyway, why would he check
> it? In many circumstances it walks, quaks, and looks like a
> duch^H^H^H^Hvoid-returning method. It's an example that essentially fits
> your requirement of an example a checked exception thrown by a
> void-returning method that seems like decent API.
See, I don't think I've ever seen someone using reflection to call a
method where they had a legitimate response that wasn't to first
simply log it, grab the wrapped exception and rethrow that. Indeed,
the very existance of InvocationTargetException is something I've
often seen lead to errors, as people mistakenly rethrow that, and not
the exception that it wraps.
> Is this a no true scotsman argument, or did we just move on to: Okay, there
> _ARE_ examples of decent usage of Checked Exceptions, but I just feel there
> aren't enough of them to warrant all the pain. Which is a fine position to
> take, just be aware that there's an inherent "personal taste" aspect to such
> a claim.
What? My claim here is you can not say that an Exception makes a
better checked exception than a runtime one without knowing the API in
which it is used. Essentially, I can't say one way or another about
whether or not the FundsException should be checked or not. I can say
that I'd probably rather the information it provides be provided
through an Either return than a checked exception. You then claimed
that there is no good api around the Either and related types. I
provided an API example that I thought fit that bill rather nicely.
True its important to know if a remote method call failed because of networking issues, but once we know by catching theres not much we can do to recover
, which makes it seem more like an environmental/runtime problem than something that can be reattempted.
Isnt it fair to say checkness should be equivalent to the ability to recover
On Fri, Mar 25, 2011 at 8:39 PM, mP <miroslav...@gmail.com> wrote:True its important to know if a remote method call failed because of networking issues, but once we know by catching theres not much we can do to recoverOn the contrary, there are plenty of things you can do, among which 1) retry according to certain policies (e.g. exponential back off), 2) let the user know, 3) log it, 4) fail, 5) try again on a different cluster node, etc...
I smell a remote ejb stub :) In practical terms end developers never try any of these simply because the API does not present an opportunity to retry on a different cluster node simply because they are not aware of the available nodes. When working w/ remote services throwing RE becomes another problem that can happen at any time like OOME
and for the sake of simplicity it probably makes sense to group it as such. A lot of Springy ppl and users seem to think this way and its got a lot going for it.
On Fri, Mar 25, 2011 at 9:20 PM, mP <miroslav...@gmail.com> wrote:
I smell a remote ejb stub :) In practical terms end developers never try any of these simply because the API does not present an opportunity to retry on a different cluster node simply because they are not aware of the available nodes. When working w/ remote services throwing RE becomes another problem that can happen at any time like OOMEI don't think the comparison to OOME is justified, because
- OOME can literally happen at any time. Really, any time.
- When OOME happens, there is very little left to do but crash.
- RemoteExceptions can only happen when you call a remote method.
- As I showed above, you can do something meaningful when a RemoteException occurs.
and for the sake of simplicity it probably makes sense to group it as such. A lot of Springy ppl and users seem to think this way and its got a lot going for it.By "a lot", did you mean hundreds of lines of meaningless stack traces in logs?Yes, I certainly agree with that :-)
--
Cédric
--
You received this message because you are subscribed to the Google Groups "The Java Posse" group.
To post to this group, send email to java...@googlegroups.com.
To unsubscribe from this group, send email to javaposse+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/javaposse?hl=en.
2011/3/26 Cédric Beust ♔ <ced...@beust.com>
I don't think the comparison to OOME is justified, because
- OOME can literally happen at any time. Really, any time.
- When OOME happens, there is very little left to do but crash.
- RemoteExceptions can only happen when you call a remote method.
- As I showed above, you can do something meaningful when a RemoteException occurs.
Hey, why not just "let it crash" for everything? It certainly works for Erlang, where *everything* is a remote call to another process. It's been used very successfully in telecoms switches with over 2 million lines of code and nine-nines reliability; a few nanoseconds of downtime annually.
--
Cédric
What? My claim here is you can not say that an Exception makes a
better checked exception than a runtime one without knowing the API in
which it is used.
I like how you call foul all the time on other people's rudeness, yet
feel free to call any design you don't care for silly on a whim.
TransferFunds could return any number of useful things, not the least
being a transferReceipt. As for why one might prefer for this to be a
runtime, it is likely something you can let bubble up all the way to a
UI layer to have a handler that captures it and presents it to the
user in an appropriate fashion. The transactions should get rolled
back no matter what the actual exception was.
Also, I linked to what I would consider a fairly elegant domain model
for trades. Not exactly the same, but pretty close. I am not looking
at it again right now, but I don't recall it relying on exceptions.
If nothing else, the Erlang approach shows us that different categorisations for FileNotFound, OutOfMemory, RemoteInvocation, etc. can also be seen as somewhat artificial when a different stance is taken regarding what exceptions are and how to handle them.
I like how you call foul all the time on other people's rudeness, yet
feel free to call any design you don't care for silly on a whim.
TransferFunds could return any number of useful things, not the least
being a transferReceipt.
As for why one might prefer for this to be a
runtime, it is likely something you can let bubble up all the way to a
UI layer to have a handler that captures it and presents it to the
user in an appropriate fashion. The transactions should get rolled
back no matter what the actual exception was.
Also, I linked to what I would consider a fairly elegant domain model
for trades. Not exactly the same, but pretty close. I am not looking
at it again right now, but I don't recall it relying on exceptions.
You know, fuck you. I never changed the goal posts. This is what
they have been the entire time. My claim from the beginning, there
are no good APIs that rely on checked exceptions. I have put forth a
monadic design, that you feel like claiming is one designed by idiots.
You do not argue in good faith at all. So, I'm done here and I
apologize for wasting everyones time trying to have a good faith
discusion.