How to deal with CheckedExceptions

316 views
Skip to first unread message

phil swenson

unread,
Mar 23, 2011, 5:43:48 PM3/23/11
to java...@googlegroups.com
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.  In reality I hate both solutions as I'd really rather just turn them off.  But that isn't doable.

Any thoughts on the pros/cons of #1 vs #2?  Or other options?


Kevin Wright

unread,
Mar 23, 2011, 5:48:51 PM3/23/11
to java...@googlegroups.com

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.

Cédric Beust ♔

unread,
Mar 23, 2011, 6:18:28 PM3/23/11
to java...@googlegroups.com, phil swenson
On Wed, Mar 23, 2011 at 2:43 PM, phil swenson <phil.s...@gmail.com> wrote:
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.

I'm quite baffled by the justifications here. All this hacking just so the stack dump is more readable? Is that really what you care the most about?

I care about my code being robust, which means handling errors in a sensible way. Sometimes, it means catching them and/or wrapping them, other times it means declaring them in my throws clause and letting the code above deal with what happened. This should be the only deciding factor in how you want to handle checked exceptions.

What you (and the author of the blog post) are advocating is basically "I'm too lazy to handle errors so I'm just going to ignore them". The author of the post even has the nerve to say "It's amazing how readable your code becomes". Well, yes, if you start ignoring error cases, your code becomes much simpler.

Instead of just putting a blanket ban on all checked exceptions, he would have been better off trying to understand which ones need to be checked and which ones should be unchecked. All he's done with his fork is making the servlet less robust.

Checked exceptions are a good idea and an indispensable component of robust software, but they are easy to misuse.

--
Cédric


phil swenson

unread,
Mar 23, 2011, 7:53:12 PM3/23/11
to java...@googlegroups.com
Opps, somehow dropped the javaposse group post on this.

---------- Forwarded message ----------
From: phil swenson <phil.s...@gmail.com>
Date: 2011/3/23
Subject: Re: [The Java Posse] How to deal with CheckedExceptions
To: Cédric Beust ♔ <ced...@beust.com>


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

Bruce Eckel, author of Thinking in Java (see Resources), says that after years of using the Java language, he has come to the conclusion that checked exceptions were a mistake -- an experiment that should be declared a failure. Eckel advocates making all exceptions unchecked, and offers the class in Listing 2 as a means for turning checked exceptions into unchecked ones while preserving the ability to catch specific types of exceptions as they are propagated up the stack (see his article in the Resourcessection for an explanation of how it can be used):

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; }
} 




2011/3/23 Cédric Beust ♔ <ced...@beust.com>

Cédric Beust ♔

unread,
Mar 23, 2011, 7:56:32 PM3/23/11
to java...@googlegroups.com



2011/3/23 phil swenson <phil.s...@gmail.com>

Thanks for the Lazy comment.  You can handle Exceptions even if they are RuntimeExceptions

Of course, but since the compiler no longer enforces it, they are easy to miss and to ignore. I much prefer the compiler getting into my face to remind me "this call can fail this way and that way, and you need to think about this right now".

Note that you only need to "think" about it. Once you do that, you decide if you want to handle it or defer it to callers. It's a very sane way of building solid code.

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

Yes, it is annoying to handle error cases, but you have to. Besides, you only need to deal with it at the level you choose. Wherever you don't care about them or can't handle them, just add a `throws` clause. That's the right way of doing it.

The wrong way is adding `throws` everywhere, because with this system, all your methods end up declaring an exception, which means that in effect, none of them do. Effectively, you have just completely disabled the exception system and all the advantages that they bring.

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

Yes, it's always baffled me that someone who claims to feel so strongly about "clean code" is so cavalier and dismissive about error cases.

It's a similar argument to the one presented in the blog post: the code "looks" clean, but it's not robust.

 
 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.

Yup. He just doesn't understand checked exceptions, like so many other people.

The important part is understanding that you need both runtime and checked exceptions. The hard part is knowing when to choose "checked", and the authors of the JDK made some terrible mistakes in that area which have given the entire concept a very bad reputation.

 

I also just found this snippet for what Bruce Eckel advocates (from http://www.ibm.com/developerworks/library/j-jtp05254.html#resources):

Same observation about Bruce, who's gone much further down the rabbit hole and who's now advocating that types are a hindrance.

--
Cédric





--
Cédric


phil swenson

unread,
Mar 23, 2011, 7:59:05 PM3/23/11
to Cédric Beust ♔, java...@googlegroups.com
The argument boils down to to costs vs benefits.

All the checked exception haters think the costs greatly out-weigh the benefits.

Costs:
1) PITA
2) Your interfaces break every time you introduce a new exception.
3) They don't scale (rippling effect can easily get out of hand)

That and lead to a bunch of people writing code like this (We've all seen it):

try {...} 
catch(Excpetion e) 
{Log.exception(e)}

or

try {...} 
catch(Excpetion e) 
{// empty clause}

The former is usually wrong in that you usually can't proceed as if everything is OK.

The latter speaks for itself.



And the Benefits?

meh.

2011/3/23 Cédric Beust ♔ <ced...@beust.com>

mP

unread,
Mar 23, 2011, 7:59:50 PM3/23/11
to java...@googlegroups.com, phil swenson
If you want to catch checked and rethrow wrapped up but hate the long and messy stacktraces you can simply solve this by copyin the stack elements from the checked to the wrapped.

mP

unread,
Mar 23, 2011, 8:05:56 PM3/23/11
to java...@googlegroups.com, phil swenson
Thread.currentThread().stop(cause); lets you throw checked exceptions

Kevin Wright

unread,
Mar 23, 2011, 8:34:33 PM3/23/11
to java...@googlegroups.com, Cédric Beust ♔
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!

If it's possible that an unexpected, *exceptional* fault may occur, and the method really has no idea about how far up the call stack you should go before it can be correctly handled, then throw an exception, but please don't expect every possible intervening method to encapsulate this possibility in its type signature.

There is no place for checked exceptions, they only appear to have value in the most trivial of examples, purpose-crafted to demonstrate the concept.


2011/3/23 Cédric Beust ♔ <ced...@beust.com>



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



--
Kevin Wright

gtalk / msn : kev.lee...@gmail.com
mail: kevin....@scalatechnology.com
vibe / skype: kev.lee.wright
quora: http://www.quora.com/Kevin-Wright
twitter: @thecoda

"My point today is that, if we wish to count lines of code, we should not regard them as "lines produced" but as "lines spent": the current conventional wisdom is so foolish as to book that count on the wrong side of the ledger" ~ Dijkstra

Josh Berry

unread,
Mar 23, 2011, 8:42:28 PM3/23/11
to java...@googlegroups.com
2011/3/23 Cédric Beust ♔ <ced...@beust.com>:

> The important part is understanding that you need both runtime and checked
> exceptions. The hard part is knowing when to choose "checked", and the
> authors of the JDK made some terrible mistakes in that area which have given
> the entire concept a very bad reputation.

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.

Russel Winder

unread,
Mar 24, 2011, 3:57:09 AM3/24/11
to java...@googlegroups.com, Cédric Beust ♔
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...@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

signature.asc

Casper Bang

unread,
Mar 24, 2011, 4:56:19 AM3/24/11
to The Java Posse
> Of course, but since the compiler no longer enforces it, they are easy to
> miss and to ignore. I much prefer the compiler getting into my face to
> remind me "this call can fail this way and that way, and you need to think
> about this right now".

See that's what separates most developers. I definitely prefer the
compiler NOT to get in my way and insist on holding my hand when it
really is just a false sense of security! Remember, checked exceptions
do not guarantee that you handle exceptional cases, they just require
you to acknowledge them. The only true guard against exceptional
cases, are unit tests. Otherwise, I'd much rather the problem gets
allowed to bubble up to the surface where I can reason about it.

There is simply no need to pollute method signatures and annoy the
developer unnecessarily, luckily the remedy is simple:
http://coffeecokeandcode.blogspot.com/2009/08/tweaking-javac-leniency.html

Phil

unread,
Mar 24, 2011, 5:16:13 AM3/24/11
to The Java Posse
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
> London SW11 1EN, UK   w:www.russel.org.uk skype: russel_winder
>
>  signature.asc
> < 1KViewDownload

Phil

unread,
Mar 24, 2011, 5:20:53 AM3/24/11
to The Java Posse
But what is an error condition? A business error or a lower level (VM
or OS) issue? It's a nice pattern for handling business logic errors
('your input is invalid' or 'a fulfulled order can't be cancelled')
but I treasure the ability to clearly separate the business logic from
the Exception handling (not error handling).

On Mar 24, 7:57 am, Russel Winder <rus...@russel.org.uk> wrote:
>
> 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
> London SW11 1EN, UK   w:www.russel.org.uk skype: russel_winder
>
>  signature.asc
> < 1KViewDownload

Kevin Wright

unread,
Mar 24, 2011, 5:33:27 AM3/24/11
to java...@googlegroups.com, Phil
On 24 March 2011 09:16, Phil <ph...@surfsoftconsulting.com> wrote:
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.


Wrap and throw?  Honestly... I'm sick and tired of writing classes that have to deal with files, and having half the source code be for wrapping and rethrowing.  Of course, I *could* have those methods also declare IOException, but that's just the boilerplate equivalent of an interest-only mortgage - pay a small amount of boilerplate interest now, and still have to pay the full cost later.
 
--
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.

Josh Berry

unread,
Mar 24, 2011, 7:07:28 AM3/24/11
to java...@googlegroups.com
On Thu, Mar 24, 2011 at 5:16 AM, Phil <ph...@surfsoftconsulting.com> wrote:
> 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.

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.

Reinier Zwitserloot

unread,
Mar 24, 2011, 7:41:14 AM3/24/11
to java...@googlegroups.com, phil swenson
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.

Josh Berry

unread,
Mar 24, 2011, 8:20:27 AM3/24/11
to java...@googlegroups.com
On Thu, Mar 24, 2011 at 7:41 AM, Reinier Zwitserloot <rein...@gmail.com> wrote:

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

Kevin Wright

unread,
Mar 24, 2011, 9:03:33 AM3/24/11
to java...@googlegroups.com, Reinier Zwitserloot, phil swenson
On 24 March 2011 11:41, Reinier Zwitserloot <rein...@gmail.com> wrote:
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

Flappant would be to state "use Haskell", or Coq, or Agda.  By comparison, Scala is significantly more acceptable to many Java developers, especially if you're already considering a tool like Lombok that will break code on any existing IDEs without the plugin.  If you're having to download special support for your IDE & build tools anyway, then you're already halfway to a different language, Lombok and Scala have exactly the same ease of adding to your toolchain (except for IntelliJ, which Lombok doesn't support)
 
Scala *is* relevant here, as is any language offering built-in support for Either/Maybe/Whatever - allowing a method to return one of two possible types.  Either the result of some successful operation or some indication of error.  Use closures to repeatedly map over the success values contained in this construct and you have a very clean, composable way to represent problems that aren't exactly "exceptional".  Unlike checked exceptions (which can be subverted), this approach truly does force callers to acknowledge the possible error condition, and does so with far less ceremony and potential for abuse.  It's possible to use a similar approach in Java, though the lack of consistent library support and closures is obviously going to make it harder.  Another tactic is also create Null objects, or Error objects, subclasses of the expected return type that express a failure without having to pervert flow control.

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.  While competition is natural and healthy, FUD is good for nobody.  I have yet to see a Scala advocate showing anything but praise for your efforts with Lombok, so it's only polite to stop firing off nothing but objections in response.


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


So checked exceptions are a good thing, but only if we, the users, develop the core Java APIs better in the first place?  Don't ask for much, do you?

 
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.

Phil

unread,
Mar 24, 2011, 9:09:52 AM3/24/11
to The Java Posse
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)

On Mar 24, 1:03 pm, Kevin Wright <kev.lee.wri...@gmail.com> wrote:
> On 24 March 2011 11:41, Reinier Zwitserloot <reini...@gmail.com> wrote:
>
>
>
> > 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-except...
> gtalk / msn : kev.lee.wri...@gmail.com
> <kev.lee.wri...@gmail.com>mail: kevin.wri...@scalatechnology.com

Phil

unread,
Mar 24, 2011, 9:14:58 AM3/24/11
to The Java Posse
Well that's kind of where I'm coming from anyway. If I'm using an API
that throws (un)checked exceptions that I can manage then I'd rather
encapsulate handling it such that the dependencies are not presented
with it. The things you really can't handle, well, it's game over. The
debate about what to do when File.close() throws an exception applies
regardless of the type of exception.

On Mar 24, 11:07 am, Josh Berry <tae...@gmail.com> wrote:

Reinier Zwitserloot

unread,
Mar 24, 2011, 11:03:46 AM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, Kevin Wright
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.

Reinier Zwitserloot

unread,
Mar 24, 2011, 11:06:47 AM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, phil swenson
Phil nailed it - it's a cost vs. benefit thing. Java is somewhat unique in having checked exceptions in the first place, and presuming we can take the entire java ecosystem as more than mere anecdotal evidence in regards to how well it works out in practice - the experiment failed. The costs do not outweigh the benefits. Nevertheless, we're stuck with it, so from a pragmatic standpoint: Use @SneakyThrows or some other sneaky throws mechanism, be very careful when adding checked exceptions to your own stuff, and campaign for a way to opt out more easily in JDK8 or 9.

Kevin Wright

unread,
Mar 24, 2011, 11:09:49 AM3/24/11
to java...@googlegroups.com


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

Thomas Ferris Nicolaisen

unread,
Mar 24, 2011, 11:10:35 AM3/24/11
to java...@googlegroups.com, phil swenson
If you've already got Google Guava on your classpath, there's something similar to Lombok in Throwables (well, maybe not as fancy, but still).

Aside from that, here's my last comment in reply to that blog - the author didn't deem necessary for publishing: http://tfnico.posterous.com/exception-hygiene

Cédric Beust ♔

unread,
Mar 24, 2011, 11:24:35 AM3/24/11
to java...@googlegroups.com, Kevin Wright, Reinier Zwitserloot, phil swenson


On Thu, Mar 24, 2011 at 6:03 AM, Kevin Wright <kev.lee...@gmail.com> wrote:
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.  

That's a low blow, I can't believe you actually wrote this about Reinier while you have been the one constantly answering "Scala" whatever the question was.

You are the one who looks threatened to me and as a consequence of your childish debating habits, my eyes usually immediately glaze over as soon as I see "Scala" in your posts. In contrast, I always read Reinier's answers in full because he only brings up Lombok when it's actually relevant. You could learn a thing or two from him.

--
Cédric


Cédric Beust ♔

unread,
Mar 24, 2011, 11:31:47 AM3/24/11
to Russel Winder, java...@googlegroups.com


2011/3/24 Russel Winder <rus...@russel.org.uk>


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?

Definitely backward looking. You end up writing the code above everywhere. Here is a quick example from the io library:

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
        }
 
Of course, guess what the caller function needs to do? That's right, the exact same gymnastics: receive two values, one is the real result and the other is the error, check the error, return early if there is one or carry on. Make another API call, repeat the dance.

In effect, you are recreating the mechanism of exceptions except that it's now infecting every other line of your code. The readability of this idiom? Terrible.

From this aspect, it seems to me that the authors of Go were put in cryogenized sleep in 1995, woken up in 2009 and asked to write a language.

Obviously, suggesting that Maybe/Option is a better solution is equally silly.

-- 
Cédric

Ricky Clarkson

unread,
Mar 24, 2011, 11:35:07 AM3/24/11
to java...@googlegroups.com, Reinier Zwitserloot, Cédric Beust ♔, Kevin Wright
A) A possibility is to rewrite those methods to return a Runnable or similar that is later applied (well, an Option<Runnable> or an Either<Failure, Runnable>).  That way you are no longer ignoring the return values as a matter of course.

Perhaps a better way there is to pass in some kind of error case handler.  I don't know the correct answer though.

B) I usually use Option as a null replacement rather than as an error case.  Its disadvantage as an error case is that it doesn't say where it came from.  You can use Either<Failure, X> for that, where Failure is whatever you want it to be, but probably a good rule is that if you think you might need to know where it came from you're talking about a software bug rather than something a program can recover from, so an unchecked exception would suffice.

C) I'm repeating myself a bit, but here's the approximate set of rules I use:

1. If there's a software bug or I'm too lazy to think about the error case at the moment, an unchecked exception will happen and that will be logged/reported.
2. If the method has void as its return type and can't easily be transformed so that callers normally consume its result, I'll use a checked exception.
3. If the method has something other than void as its return type I'll use Option/Either or whatever seems appropriate.  It's not uncommon to invent your own types similar to Option, e.g., I had one named UserResponse that would either hold a String containing the user's answer to a question, or would represent that the user had entered nothing, or that the user had cancelled the dialog.  data UserResponse = Response s | Empty | Cancelled -- to express it in Haskell.

--

Carl Jokl

unread,
Mar 24, 2011, 11:44:49 AM3/24/11
to The Java Posse
Another aspect of dropping exceptions is the lost of the stack trace.
A good stack trace is very useful in establishing what went wrong and
where in a program.

Having done a bit of C# development where exceptions are not checked
there were some times when I missed them. One of my coworkers tended
to be quite sloppy / blasé about catching exceptions in code and
sometimes it would have been good to know what my program might need
to handle. The check exceptions in Java can be seen as part of the
documentation. I was caught out at least once when an exception was
thrown by a library which was being used but the specific exception
was not mentioned in the documentation as being potentially thrown. I
know that this was a documentation issue but still, I think checked
exceptions help me be more aware of what things I need to handle
without having to keep referring to the documentation.

Ricky Clarkson

unread,
Mar 24, 2011, 11:54:55 AM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, Russel Winder
Obviously, suggesting that Maybe/Option is a better solution is equally silly.

It is a better solution, because it doesn't have to affect readability the same way.  Consider the difference between:

Go (probably incorrect, I don't speak that language):

x, err = getMeAnX()
if (isError(err))
    return -1, err
y, err = getMeAY()
if (isError(err))
    return -2, err
return x + y

Idiomatic Java:

class XY implements FixedInterface {
    public int execute() {
        int x;
        try {
            x = getMeAnX();
        } catch (NoXException e) {
            throw new RuntimeException(e);
        }
        int y;
        try {
            y = getMeAY();
        } catch (NoYException e) {
            throw new RuntimeException(e);
        }
        return x + y;
    }
}

Java with Option:

class XPlusY implements FixedInterface {
    public Option<Integer> execute() {
        for (int x: getMeAnX())
            for (int y: getMeAY())
                return Option.some(x + y);
        return Option.none();
    }
}

Scala, just for fun:

def execute = for (x <- getMeAnX; y <- getMeAY) yield x + y

or

def execute = getMeAnX.bind(x => getMeAY.map(y => x + y))

The line above can be translated to Java fairly mechanically but I'm not sure that would add anything to the debate apart from lots of lines.

Kevin Wright

unread,
Mar 24, 2011, 11:59:32 AM3/24/11
to Cédric Beust ♔, java...@googlegroups.com, Reinier Zwitserloot, phil swenson


2011/3/24 Cédric Beust ♔ <ced...@beust.com>
Is this clash so unusual?  Lombok offers a clean subset of Scala's functionality, so it's only natural that the two would arise in response to the same issues. It's a natural solution where Scala is not an option (lack of familiarity, opportunity cost for the time to learn it, corporate policy, not breaking consistency in an existing codebase, or simply not wanting to use Scala for whatever reason)
 
and yes, Scala is relevant in more cases than Lombok.  It does more, so this is hardly surprising.

--
Cédric


Kevin Wright

unread,
Mar 24, 2011, 12:31:59 PM3/24/11
to java...@googlegroups.com, Reinier Zwitserloot, Cédric Beust ♔
On 24 March 2011 15:03, Reinier Zwitserloot <rein...@gmail.com> wrote:
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).

C-style error codes are perfectly natural where the closest you have to pattern-matching on alternate possibilities is a switch statement that only handles integers.  Exceptions often seem to be a better fit, not because there's any benefit to returning data via a side channel, but because exception *handlers* offer richer pattern-matching semantics.  
 
The issue here isn't return statements, but what language constructs are available for structure and flow control in the language.  Don't point to nested if/else statements as showing the inadequacy of return values when you should be pointing to exception handlers as showing the inadequacy of nested if/else statements.

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

The following two definitions are directly equivalent:

String someMethod(String input) throws FileNotFoundException
Either<FileNotFoundException, String> someMethod(String input)

The differences being:
  • Java has specialised construct to ease the task of exception handling, but lacks constructs to simplify working with data inside the right-hand side of an "Either"
  • "throws" is returning data via a sideband channel, and isn't part of the core method signature
  • Either could just as easily return some error type, not just exceptions (it could be a string for display to the end user)
  • Uses exceptions always forces an expensive stack trace to be built, if if not needed
  • When using "Either", it's the method that decides if it must be explicitly handled, not the type hierarchy of the exception type
This last point is significant, imagine I had two methods:

void logImportantTransactionDetailsForLegalCompliance
void saveActiveDocument

In both cases, the file may not be found, so a FileNotFoundException seems appropriate.  For the first method, I'd want to enforce that that exception is caught asap, in the second, I want it to propogate back to the UI through several layers of stack.

by having a return type of Option<Exception> in the first case, and an unchecked exception in the second case, I can do this.  But with the checked variety, it's all or nothing, as the Exception type determines if it must be checked, not the thrower.

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

Exactly the same as for checked exceptions, you either handle it or pass up the stack.  This is a domain design issue though, not something that can be correctly answered at the language level.

Option is typically used wherever a null would be expected in java to indicate "no value", such as looking up the value for an undefined key in a map.  (question, how best would you disambiguate the case where it does hold a value, but that value is null?) The problem being solved is how to compose a sequence of operations that may or may not have a return value/error.  The missing piece of the puzzle is closures, allowing you to do stuff like:

val x: Option[Int] = Some(7)
val y = x map (2 * _) //returns Some(14)

if x was None, this would return None.  No errors, no NullPointerExceptions, it just works.  You can do the same thing to map-over the right-hand-side of an Either, while leaving intact any Error held by the left hand side.  Likewise, you can map over the left hand side to convert (for example) an exception to a message string.

Edward Gabriel Moraru

unread,
Mar 24, 2011, 12:32:01 PM3/24/11
to java...@googlegroups.com
I would write the idiomatic Java this way:

class XY implements FixedInterface {

    public int execute() {
        try {
            int x = getMeAnX();
            int y = getMeAY();

            return x + y;
        } catch (NoXException e) {
            throw new RuntimeException(e);
        } catch (NoYException e) {
            throw new RuntimeException(e);
        }
    }
}

so that the non-exceptional flow is not masked by the treatment of exceptions.
Maybe is a matter of taste, but for me it seems more readable.
I would use the initial layout only if I had something special to do for every exception something like:

class XY implements FixedInterface {
    public int execute() {
        int x;
        try {
            x = getMeAnX();
        } catch (NoXException e) {
            //do something special here
           //some special processing ?
            throw new RuntimeException(e);
        }
        int x1;
        try {
            x1 = getMeAnX();
        } catch (NoXException e) {
            //do something extra-special here
            //extra special processing
            throw new RuntimeException(e);
        }
        int y;
        try {
            y = getMeAY();
        } catch (NoYException e) {
            throw new RuntimeException(e);
        }
        return x + x1 + y;
    }
}

Regarding the issue of checked exceptions I'd say that all of bad things about them stems from IOException and SQLException.
Those 2 have tormented a lot of programmers and are the poster childs of bad checked exception usage.

My 2 cents,
Edward.

P.S. : This debate sounds a lot like the one about OO and Functional, btw.
P.P.S. : damn, it's so hard to write code in the GMail editor ;)

Edward Gabriel Moraru

unread,
Mar 24, 2011, 12:36:03 PM3/24/11
to java...@googlegroups.com
children instead of childs, d'oh! english is even harder than Java :P

Josh Berry

unread,
Mar 24, 2011, 12:52:42 PM3/24/11
to java...@googlegroups.com
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.

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

Cédric Beust ♔

unread,
Mar 24, 2011, 1:00:03 PM3/24/11
to java...@googlegroups.com, Edward Gabriel Moraru


On Thu, Mar 24, 2011 at 9:32 AM, Edward Gabriel Moraru <edward...@gmail.com> wrote:
Regarding the issue of checked exceptions I'd say that all of bad things about them stems from IOException and SQLException.

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.

--
Cédric


phil swenson

unread,
Mar 24, 2011, 12:58:19 PM3/24/11
to java...@googlegroups.com
awful.  The only people I hear saying Exceptions in general bad are 1) Joel Spolksy 2) Go lang and 3) Objective C purists.  They are crazy!  There is a reason Exceptions were invented and are offered by every major language in use.

2011/3/24 Cédric Beust ♔ <ced...@beust.com>

Cédric Beust ♔

unread,
Mar 24, 2011, 12:57:53 PM3/24/11
to Kevin Wright, java...@googlegroups.com, Reinier Zwitserloot


2011/3/24 Kevin Wright <kev.lee...@gmail.com>

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

Of course not, exceptions also allow someone else than your direct caller to handle the error without you having to bubble up this condition manually.

--
Cédric


phil swenson

unread,
Mar 24, 2011, 12:55:01 PM3/24/11
to java...@googlegroups.com, Phil
I consider the tendency to "handle where the exception happens" to be a Checked Exception caused anti-pattern.  The intent of "handle where the exception happens" usually results in the opposite of it's intent.  It tends to mask/hide errors and leave the application in a bad state (bad data integrity for example).

Not that it's NEVER valid, but it usually isn't.  The sorts of things that cause exceptions can't usually be handled - most of them occur because of bugs or system failures.  And most apps simply won't work correctly if your database is down, they can't hit a web service, sql insert fails, file is missing/can be saved....

So IMO the best general pattern is to let the exception bubble up to the top level thread and log/display/notify the user. Note that log/display/notify the user is very much not "throw and forget".  There are cases where you can gracefully handle of course, but I've found these to be less than 10% of exception cases.

This is the pattern that is common in all other languages without checked exceptions.  You default to letting them bubble/handle at the top, and if you identify a case where the application can/should handle then you put code in for that.

On Thu, Mar 24, 2011 at 3:16 AM, Phil <ph...@surfsoftconsulting.com> wrote:
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
> London SW11 1EN, UK   w:www.russel.org.uk skype: russel_winder
>
>  signature.asc
> < 1KViewDownload

phil swenson

unread,
Mar 24, 2011, 1:09:36 PM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, Edward Gabriel Moraru
I'll grant you that I'd care a hell of a lot less about it!

2011/3/24 Cédric Beust ♔ <ced...@beust.com>
Cédric


Alexey Zinger

unread,
Mar 24, 2011, 1:14:47 PM3/24/11
to java...@googlegroups.com
Except that's not how it would be done in Java.

try {
 return getMeAnX() + getMeAY();
}
catch(NoXException e) {
  throw new RuntimeException(e);
}
catch(NoYException e) {
  throw new RuntimeException(e);
}
 
Alexey



From: Ricky Clarkson <ricky.c...@gmail.com>
To: java...@googlegroups.com
Cc: Cédric Beust ♔ <ced...@beust.com>; Russel Winder <rus...@russel.org.uk>
Sent: Thu, March 24, 2011 11:54:55 AM
Subject: Re: [The Java Posse] How to deal with CheckedExceptions

Cédric Beust ♔

unread,
Mar 24, 2011, 1:30:28 PM3/24/11
to java...@googlegroups.com, Josh Berry


On Thu, Mar 24, 2011 at 10:23 AM, Josh Berry <tae...@gmail.com> wrote:
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.

FileNotFound.

--
Cédric


Edward Gabriel Moraru

unread,
Mar 24, 2011, 1:37:58 PM3/24/11
to java...@googlegroups.com
SQLException on Statement.executeXXX() methods but never thrown by Connection.close()

2011/3/24 Cédric Beust ♔ <ced...@beust.com>

Alexey Zinger

unread,
Mar 24, 2011, 1:43:10 PM3/24/11
to java...@googlegroups.com
I'd say the problem with IOException is not that it should have been unchecked, but that it's permeated I/O API in a way that painted with too broad a brush.  There are calls that should throw checked exceptions and others that should throw unchecked exceptions.  The way I would decide which I/O API should throw what kind of exception is as follows: if the call is likely following at least one other interaction with the underlying resource, the exception should be unchecked; but if it's likely the first call to the resource, it should be a checked exception.  To illustrate this point, if we're opening a stream on a file, we know nothing about the state of the file, so we may very well have a problem that needs to be explicitly addressed.  But having opened said stream successfully, writing/reading and closing are things that are extremely unlikely to fail.  And if they did, the programmer is in the best possible position to decide whether this thing should be bubbled up to the top or if it can be recovered from.

Similar principles can be devised for other kinds of API.  The problem with checked exceptions in Java is not that their very presence, but their application in standard libraries.
 
Alexey



From: Josh Berry <tae...@gmail.com>
To: java...@googlegroups.com
Sent: Thu, March 24, 2011 1:23:26 PM

Subject: Re: [The Java Posse] How to deal with CheckedExceptions

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.

--
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+unsub...@googlegroups.com.

Kevin Wright

unread,
Mar 24, 2011, 1:49:48 PM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, Josh Berry


2011/3/24 Cédric Beust ♔ <ced...@beust.com>
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.

c) See previous discussions for my alternate design of a sane filesystem API
 
--
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.



--

Ricky Clarkson

unread,
Mar 24, 2011, 1:36:07 PM3/24/11
to java...@googlegroups.com, Alexey Zinger
You're right, Alexey.  I take it all back.  Better example needed.

Josh Berry

unread,
Mar 24, 2011, 1:51:42 PM3/24/11
to java...@googlegroups.com
On Thu, Mar 24, 2011 at 1:43 PM, Alexey Zinger <inlin...@yahoo.com> wrote:
> Similar principles can be devised for other kinds of API.  The problem with
> checked exceptions in Java is not that their very presence, but their
> application in standard libraries.

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?"

Kevin Wright

unread,
Mar 24, 2011, 1:56:29 PM3/24/11
to Cédric Beust ♔, java...@googlegroups.com, Reinier Zwitserloot


2011/3/24 Cédric Beust ♔ <ced...@beust.com>
Exceptions, yes, checked exceptions, no.

As with everyone else here, I have no issue with exceptions per-se, just the anti-patterns that so often arise around the use of *checked* exceptions.
 
--
Cédric


Casper Bang

unread,
Mar 24, 2011, 1:56:46 PM3/24/11
to The Java Posse
On Mar 24, 4:44 pm, Carl Jokl <carl.j...@gmail.com> wrote:
> Another aspect of dropping exceptions is the lost of the stack trace.
> A good stack trace is very useful in establishing what went wrong and
> where in a program.

Hmm but to be honest, many other programming languages prior to Java
were far better at pinpointing the *actual* problem. In a modern Java
stack you have warning and errors thrown left and right, and uber-
frameworks like Spring generate stack-traces you can actually see from
space!

> Having done a bit of C# development where exceptions are not checked
> there were some times when I missed them.

The full story is that the designers of C# were not convinced that
they were worth the trouble. Indeed on the .NET platform you can opt-
in using code contracts which goes far beyond checking failure
invariants (which is all a checked exception is). [http://
blogs.msdn.com/b/bclteam/archive/2008/11/11/introduction-to-code-
contracts-melitta-andersen.aspx]

Cédric Beust ♔

unread,
Mar 24, 2011, 1:57:50 PM3/24/11
to Kevin Wright, java...@googlegroups.com, Josh Berry
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 scenario

You 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


Alexey Zinger

unread,
Mar 24, 2011, 2:01:58 PM3/24/11
to java...@googlegroups.com
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.
 
Alexey


Sent: Thu, March 24, 2011 1:51:42 PM

Subject: Re: [The Java Posse] How to deal with CheckedExceptions

Josh Berry

unread,
Mar 24, 2011, 1:23:26 PM3/24/11
to java...@googlegroups.com
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 Beust ♔

unread,
Mar 24, 2011, 2:06:08 PM3/24/11
to java...@googlegroups.com, Alexey Zinger
On Thu, Mar 24, 2011 at 11:01 AM, Alexey Zinger <inlin...@yahoo.com> wrote:
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.

Interesting observation. Indeed, when exceptions are well designed in a framework, you just don't think about them. It's a bit like system administrators: when they are doing a great job, you forget they even exist.

Spring is famous for having gone 100% runtime exceptions, and the least we can say is that Spring users are not exactly quiet about Spring's exception handling...

-- 
Cédric


Josh Berry

unread,
Mar 24, 2011, 2:10:35 PM3/24/11
to java...@googlegroups.com
2011/3/24 Cédric Beust ♔ <ced...@beust.com>:

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.

Kevin Wright

unread,
Mar 24, 2011, 2:12:02 PM3/24/11
to Cédric Beust ♔, java...@googlegroups.com, Josh Berry


2011/3/24 Cédric Beust ♔ <ced...@beust.com>



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 scenario

You are very unlikely to see one, unless you use a runtime exception, which you will most likely forget to handle.

Of course not, hence my desire to not waste time and resources building an in-memory representation of the thing!
 

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.
 
Very often, I'll write code that just can't do *anything* if a particular file is not found.  In that case the thing should propagate to the top-level exception handler where it can simply be reported as-is, awaiting user input.


--
Cédric


Cédric Beust ♔

unread,
Mar 24, 2011, 2:00:00 PM3/24/11
to java...@googlegroups.com, Casper Bang


On Thu, Mar 24, 2011 at 10:56 AM, Casper Bang <caspe...@gmail.com> wrote:
> Having done a bit of C# development where exceptions are not checked
> there were some times when I missed them.

The full story is that the designers of C# were not convinced that
they were worth the trouble.

Actually, no. The full story is that .net could not support checked exceptions for backward compatibility reasons. Anything else you hear is post rationalization.

By the way, this is the very same reason why C++ couldn't have checked exceptions either.

--
Cédric


Kevin Wright

unread,
Mar 24, 2011, 2:20:33 PM3/24/11
to java...@googlegroups.com, Cédric Beust ♔, Casper Bang


2011/3/24 Cédric Beust ♔ <ced...@beust.com>
C++ works a bit differently, where specifying exceptions is supposed to enforce that you can ONLY throw the declared exceptions - opposite to to approach Java takes, where declared exceptions are added to the runtime exceptions that can be thrown regardless.

There's a good write-up of it here: http://www.gotw.ca/publications/mill22.htm


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

Casper Bang

unread,
Mar 24, 2011, 2:42:32 PM3/24/11
to The Java Posse
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?

On Mar 24, 7:00 pm, Cédric Beust ♔ <ced...@beust.com> wrote:

Cédric Beust ♔

unread,
Mar 24, 2011, 3:32:11 PM3/24/11
to java...@googlegroups.com, Casper Bang
On Thu, Mar 24, 2011 at 11:42 AM, Casper Bang <caspe...@gmail.com> wrote:
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?

.net was new but it still had to deal (interoperate) with a huge legacy, an in particular 1) COM and 2) C++.

After solving the universal binary problem with COM, Microsoft wanted to extend the same universality to languages, so IL came into the picture. Back then, they still had plans to create at least a backend that could accomodate C++, i.e. a C++ compiler that would generate IL code and be able to run on the .net platform. In the end, they decided to simply create a brand new language instead (C#) but the necessity to interoperate with old generation COM based languages remained, and neither of these languages supported checked exceptions (including VB).

--
Cédric


phil swenson

unread,
Mar 24, 2011, 3:32:36 PM3/24/11
to java...@googlegroups.com
Dunno how backwards compatibility could possibly matter on a greenfield project (C#)...

I suggest reading this interview with Anders Hejlsberg (Turbo Pascal/Delphi/C# architect):  http://www.artima.com/intv/handcuffs3.html

A couple choice quotes:
 "It is funny how people think that the important thing about exceptions is handling them. That is not the important thing about exceptions. In a well-written application there's a ratio of ten to one, in my opinion, of try finally to try catch. "

"The scalability issue is somewhat related to the versionability issue. In the small, checked exceptions are very enticing. With a little example, you can show that you've actually checked that you caught the 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."






Casper Bang

unread,
Mar 25, 2011, 1:00:30 AM3/25/11
to The Java Posse
Still, that's a far cry from declaring they could not support checked
exceptions in the language! Since it's entirely a compiler matter,
they absolutely could've chosen to support checked exceptions and wrap
runtime constraints in these. I mean, come on, much of the Java
runtime stuff calls directly down to the native layer C where there's
also no existence of checked exceptions. So sorry, I can't possibly
see how anyone could buy your explanation.


On Mar 24, 8:32 pm, Cédric Beust ♔ <ced...@beust.com> wrote:

mP

unread,
Mar 25, 2011, 1:43:25 AM3/25/11
to java...@googlegroups.com, Casper Bang
So what if theres some c/native stuff in there, you can still throw exceptions from JNI and thats exactly what happens in certain cases.

Casper Bang

unread,
Mar 25, 2011, 2:09:15 AM3/25/11
to The Java Posse
But if you wanted to encapsulate some of this with checked exceptions,
you'd just have to catch these (and possible look at various error
codes and flags) and rethrow as C# checked exceptions. They chose not
to do that, they chose not to introduce the concept into the language,
they chose to make the compiler less anal than Java's.

Reinier Zwitserloot

unread,
Mar 25, 2011, 5:34:00 AM3/25/11
to java...@googlegroups.com, Casper Bang
Monster traces still contain useful info, though perhaps the way they are rendered by most loggers, IDEs, etcetera could use some help. At some point that stack trace devolves more into a blueprint for a debugger or VM inspector to load then for something a human ought to be scanning.

I also like python's style more (a python stack trace inverses the ordering compared to a java stack trace - the deepest method is listed LAST, vs. java where its listed first). The same can usually be said for causality chains: If an exception bubbles up so far that it gets handled via error dialog / logging (the right kind of logging, i.e. at the container level, not the wrong 'catch, log, forget' anti-pattern), and you're actually looking at it to try and figure out what happened, looking at the deepest item in the causality chain is usually more enlightening.

So, yes, giganto-traces are an annoying nit, but it only takes me maybe 20 more seconds to delve through it and find the appropriate location to look, I definitely want all of it in case its more complicated than that, and at least in theory I think if this grows into too much of a problem better ways of rendering the trace could be written.

Reinier Zwitserloot

unread,
Mar 25, 2011, 5:37:10 AM3/25/11
to java...@googlegroups.com, Kevin Wright
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.

Reinier Zwitserloot

unread,
Mar 25, 2011, 5:55:50 AM3/25/11
to java...@googlegroups.com, Josh Berry

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.


wrap-and-throw is vastly superior to 'Oops I forgot to check the error code'. One will either get your compiler to yell at you until you acknowledge it, or at least will end up bubbling the error, including useful logistical data about what and where, to some level that will eventually handle it as an error / bug (render to user, dump into a log, emit to terminal, highlight debug stack trace, etc).

So, I don't really understand why its even relevant for me to name an example here.

nevertheless, can do: OutputStream.close() or OutputStream.write(). java.lang.reflect.Method.invoke (does not return void, but when I know I'm calling a void method I'm not going to bother checking the return type - resulting in the error being ignored if the return type is also used to ferry an error condition). SomeDbLibrarysTransactionObject.close().

I'm sure I could make a long long list if I ran some analysis on a bunch of commonly used APIs. 
 

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


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 about: Do we do this with an exception, or an Option/Either return value? Multiple styles to accomplish the same thing are bad. (One of the reasons I don't really like checked exceptions and just think it should all be unchecked exceptions, or at the very least, one should be able to opt out of preserving the chain when dealing with checked exceptions, is that it takes away / makes far less relevant the stylistic choice of going with a checked or unchecked exception).
 


I'm still waiting for examples of some good usages of checked exceptions.


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.

mP

unread,
Mar 25, 2011, 6:14:18 AM3/25/11
to java...@googlegroups.com, phil swenson
One fault with checked exceptions is how inheritence was used to group what is checked and what is unchecked. Unfortunately an analysis of the JDK etc seems to show that exceptions use inheritence as a grouping mechanism. The JDK often establishes a base exception for a sub system and has all related exceptions extend that.

2 Examples:

java.io.*
   IOException // generally not recoverable probably should be unchecked
    FileNotFound // probably makes sense to be checked, so programs are forced to handle and maybe ask user again.
       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.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

mP

unread,
Mar 25, 2011, 6:48:48 AM3/25/11
to java...@googlegroups.com, Josh Berry
One fault with checked exceptions is how inheritence was used to group what is checked and what is unchecked. Unfortunately an analysis of the JDK etc seems to show that exceptions use inheritence as a grouping mechanism. The JDK often establishes a base exception for a sub system and has all related exceptions extend that.

2 Examples:

java.io.*
   IOException // generally not recoverable probably should be unchecked
    FileNotFound // probably makes sense to be checked, so programs are forced to handle and maybe ask user again.
       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. Maybe keyword might have helped.

Kevin Wright

unread,
Mar 25, 2011, 6:56:07 AM3/25/11
to java...@googlegroups.com


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.

Josh Berry

unread,
Mar 25, 2011, 7:33:41 AM3/25/11
to java...@googlegroups.com
On Fri, Mar 25, 2011 at 5:55 AM, Reinier Zwitserloot <rein...@gmail.com> wrote:
> wrap-and-throw is vastly superior to 'Oops I forgot to check the error
> code'. One will either get your compiler to yell at you until you
> acknowledge it, or at least will end up bubbling the error, including useful
> logistical data about what and where, to some level that will eventually
> handle it as an error / bug (render to user, dump into a log, emit to
> terminal, highlight debug stack trace, etc).
> So, I don't really understand why its even relevant for me to name an
> example here.
> nevertheless, can do: OutputStream.close() or OutputStream.write().
> java.lang.reflect.Method.invoke (does not return void, but when I know I'm
> calling a void method I'm not going to bother checking the return type -
> resulting in the error being ignored if the return type is also used to
> ferry an error condition). SomeDbLibrarysTransactionObject.close().
> I'm sure I could make a long long list if I ran some analysis on a bunch of
> commonly used APIs.

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

Reinier Zwitserloot

unread,
Mar 25, 2011, 8:42:17 AM3/25/11
to java...@googlegroups.com, Josh Berry
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.

... that's what those examples are listing. I noticed you conveniently "forgot" InsufficientFundsException and InvocationTargetException. Feel free to say that these corner cases don't outweigh the bad side of checked exceptions (you'll hear no argument from me on that one), but you just ignored them and then asked me again to list examples, in a rude tone of voice too. I found it offensive. Please mind your tone and definitely don't cherry-pick in a counterargument!

 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?

A lot. I mentioned OutputStream. If OutputStream.close() fails, that's as good as any of the writes failing, as it might be a caching stream, and the close() was simply the first opportunity for flush. This is for example for network connections _definitely_ an expected thing that could happen.

Returning a 'fail' return value from .close() would suck, as 99% of all java programmers would ignore it, and thus silently ignore the fact that their entire write out just failed entirely. The action to be taken here is to either use an alternate way to write the data, and failing that, to convey an error to the user / log / etc. This should be done by letting the IOException bubble up (which is why it should be possible to tell the compiler to just let the IOException bubble even if I don't manually 'throws' it, because I can't due to an interface restriction). I'm very much open to the argument that IOException (or whatever Exception .close() would throw) is to be unchecked, but error-via-return-value would suck horrible here. Also, this isn't a very clear cut case of "This exception should have been unchecked".

   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. Unless, however, you suggest we all start from scratch, we need to deal with it. Which means either (A) an explicit opt-out mechanism, or (B) doing away with the concept of 'checked exception' altogether (they'd all be unchecked).
 

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.


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


yes, because returning a value from .close() to convey error conditions is a horrible, horrible idea, and the random RuntimeException set (OutOfMemory, NPE and friends) can happen just about everywhere, so if all is to be conveyed with return types, then _EVERY_ _SINGLE_ _METHOD_ would have to do it, at which point you've rebuild the exception mechanic in a really crappy way.

Thus (unchecked) exceptions are a given, and once you have them, its less convoluted to use them for more, than to introduce an alternate style that is completely different and the line between "When I should use an Either, and when should I throw an exception" is grey. Which it is. Thus, everything-as-an-exception is superior. I'm not implying either that checked exceptions are good or bad, but I am concluding that error-via-return-value is almost universally a bad idea, especially for the java ecosystem.
 

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'm not your monkey to order around to dance. A little more courtesy would be nice. In fact, this is really _really_ rude of you to throw in my face. 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


Note that .transferFunds(), a hypothetical method in a banking app (and typically something that isn't open source and thus not something I can point you to without breaking a bunch of NDAs), has a void return method, and failing to handle the "Oh, oops, balance isn't sufficient to cover this one" is a very very very serious error here.

I guess it's time for a caveat: I want the ability to explicitly ignore checked exceptions, @SneakyThrows style. If for whatever reason that's off the table, I'd prefer that all exceptions are unchecked. I really don't want anything to do with error-via-return-type APIs. The reasoning here is that in practice, especially in the java ecosystem (and in haskell's and scala's and every other language's too, if they were as widespread and popular as java), library authors tend to make mistakes, library APIs are virtually impossible to change once written, and with 'all exceptions are runtime exceptions', there's no need to make choices, and the pain of an API author making the wrong choice is thus alleviated. Besides, even in a perfect ponies and rainbows world where checked exceptions (or Either + uncheckeds) were done perfectly right by all participants in the ecosystem, the benefit over all-unchecked is marginal to non-existent and we definitely don't live in a ponies and rainbows world. I'm defending checked exceptions here and there because of what I feel are rather specious arguments against it, such as first asking for examples and then ignoring 2 decent ones.

Reinier Zwitserloot

unread,
Mar 25, 2011, 8:45:57 AM3/25/11
to java...@googlegroups.com
On Friday, March 25, 2011 11:14:18 AM UTC+1, mP wrote:
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

This would not work all that well without abandoning the ability for exceptions to be grouped based on type, which is also useful. If for example IOEx was unchecked, but FNFEx was checked, and RemoteEx was unchecked (which is what you propose), then declaring that you "throw IOException" is not sufficient to force callers to acknowledge the FNFEx, assuming you throw it. So what happens when I try this stunt:

IOException ex = new FileNotFoundException(...);
throw ex;

How'd the compiler figure this out? It would have to enforce a new standard for exceptions and basically disable or severely curtail their object-ness, for example by requiring all throw statements to be of the form "throw new Something();" and not just "throw someVar;". This is a problem too, because exceptions are also used as data objects that can be introspected to learn more about what went wrong.

Kevin Wright

unread,
Mar 25, 2011, 8:57:06 AM3/25/11
to java...@googlegroups.com, Reinier Zwitserloot
If we must have checked exceptions, then why not just let the thrower determine "checkedness".  You can throw anything you want, and you can put anything you want in a throws specification.

If it's in the specification then the caller has to handle it, by simply rethrowing as an unchecked exception if necessary.  This whole class hierarchy business just seems to be a guaranteed source of problems.

JodaStephen

unread,
Mar 25, 2011, 9:04:52 AM3/25/11
to The Java Posse
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

Josh Berry

unread,
Mar 25, 2011, 9:29:32 AM3/25/11
to java...@googlegroups.com
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.
>
> ... that's what those examples are listing. I noticed you conveniently
> "forgot" InsufficientFundsException and InvocationTargetException. Feel free
> to say that these corner cases don't outweigh the bad side of checked
> exceptions (you'll hear no argument from me on that one), but you just
> ignored them and then asked me again to list examples, in a rude tone of
> voice too. I found it offensive. Please mind your tone and definitely don't
> cherry-pick in a counterargument!

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.

Kevin Wright

unread,
Mar 25, 2011, 9:34:53 AM3/25/11
to java...@googlegroups.com, JodaStephen
On 25 March 2011 13:04, JodaStephen <scole...@joda.org> wrote:
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.

Not possible.  Throws clauses are erased, just as collection elements are, and are only checked by the compiler and not the runtime (hence the ability to even write @sneakyThrows or to "chuck" them without requiring a RuntimeException wrapper)

Checked exceptions are more of a shadow type system, not so much extending it as running alongside it.  Essentially, they offer a sideband return channel.

Given the availability of "Either", true pattern matching, and monadic comprehension in Scala, there's no need for this kind of hackery.  An exception (or any other type) can simply be offered up as a possible alternative return value via the usual return mechanism.

Unchecked exceptions can then be quite correctly reserved for things that are... well... exceptional!

 
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.

Reinier Zwitserloot

unread,
Mar 25, 2011, 10:57:12 AM3/25/11
to java...@googlegroups.com, Josh Berry
On Friday, March 25, 2011 2:29:32 PM UTC+1, Josh Berry wrote:
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.)



How did I 'screw with quote trees'? All my quotations have been in order and from a single post. You did not elaborate on either InvocationTargetExceptions or InsufficientFundsException anywhere in your response, but you did ask me again to list examples. What did I miss?

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,


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.
 

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.

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. 

Ricky Clarkson

unread,
Mar 25, 2011, 11:38:34 AM3/25/11
to java...@googlegroups.com, Kevin Wright, JodaStephen
Throws clauses are not erased, they are present in the bytecode but ignored by the runtime.  You're confusing that with erasure, whereby objects don't 'know' their type, only their class.

Kevin Wright

unread,
Mar 25, 2011, 1:29:22 PM3/25/11
to Ricky Clarkson, java...@googlegroups.com, JodaStephen
Yes and No, variables, parameters and method return values also retain generic parameter information, this being available via reflection and to the compiler.  It's object instances where this stuff is erased.

throws declarations follow a similar pattern, they exist in bytecode, but get ignored by the runtime and are lost in JIT compilation.  The analogy breaks down a bit here, as methods aren't first class types, and can't exactly be instantiated.

Cédric Beust ♔

unread,
Mar 25, 2011, 3:21:50 PM3/25/11
to java...@googlegroups.com, mP, phil swenson
On Fri, Mar 25, 2011 at 3:14 AM, mP <miroslav...@gmail.com> wrote:

       RemoteException // probably the most famous this should be unchecked exception

I disagree. RemoteException (and network exceptions in general) should be checked exceptions.

It's one of the things we learned from the seminal paper "A note on distributed computing" (PDF): remote operations need to be clearly separated from local operations, and the only robust way to do this is by enforcing the handling of errors statically. If you're invoking a method and the invocation operation itself (not the method) can fail, you need to handle it.

 
       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.

Yes, although all you need to achieve this goal is two different hierarchies, which we already have. It's just a pity that such a huge chunk of the inheritance tree belongs to the "checked" side.

An interesting idea that came out of last time we had this discussion was that the same exception could be checked or unchecked depending on where it's being used. The call site is obviously not the right place to do that, but the throw site might be. I'm still undecided on this whole idea.

--
Cédric


Cédric Beust ♔

unread,
Mar 25, 2011, 3:28:17 PM3/25/11
to java...@googlegroups.com, Josh Berry
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


phil swenson

unread,
Mar 25, 2011, 3:31:18 PM3/25/11
to Cédric Beust ♔, java...@googlegroups.com, mP
"An interesting idea that came out of last time we had this discussion was that the same exception could be checked or unchecked depending on where it's being used. The call site is obviously not the right place to do that, but the throw site might be. I'm still undecided on this whole idea."

Yep - no one agrees on what should be checked/unchecked.  I personally would say never checked.  Most agree SQL shouldn't be checked.  And some think it depends on the usage.

Has Sun/Oracle ever seriously considered doing anything about the Exception debacle?  I submitted a request a ways back and it got shot down very quickly.   I kind of think we're just stuck with Checked Exceptions as long as Java is used.  I doubt any other language will pick up the feature, so eventually we'll be free of them.

2011/3/25 Cédric Beust ♔ <ced...@beust.com>

Kevin Wright

unread,
Mar 25, 2011, 3:37:29 PM3/25/11
to java...@googlegroups.com, Cédric Beust ♔, Josh Berry


2011/3/25 Cédric Beust ♔ <ced...@beust.com>



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.

As opposed to:

"you still end up having to 1) have all your methods declare they could throw the exception or b) having to wrap it, most likely in some generic RuntimeException, thus losing valuable type information from your method signatures"

And what exactly is "doing all the bubbling yourself" if it isn't having all relevant methods return an Either?

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.

Serge Boulay

unread,
Mar 25, 2011, 6:03:14 PM3/25/11
to java...@googlegroups.com
How is average "java joe" suppose to get checked exceptions right if there is this much confusion around the proper usage?

2011/3/25 Cédric Beust ♔ <ced...@beust.com>

JodaStephen

unread,
Mar 25, 2011, 6:36:04 PM3/25/11
to The Java Posse
On Mar 25, 7:31 pm, phil swenson <phil.swen...@gmail.com> wrote:
> Has Sun/Oracle ever seriously considered doing anything about the Exception
> debacle?  I submitted a request a ways back and it got shot down very
> quickly.   I kind of think we're just stuck with Checked Exceptions as long
> as Java is used.  I doubt any other language will pick up the feature, so
> eventually we'll be free of them.

I submitted a proposal "lone throws" for Project Lambda to add a
language feature to allow checked exceptions more easily -
http://mail.openjdk.java.net/pipermail/lambda-dev/2010-June/001544.html
http://www.jroller.com/scolebourne/entry/exception_transparency_and_lone_throws
- It was considered and rejected. I believe that Brian Goetz is very
much in favour of checked exceptions, thus I'm not expecting Oracle's
opinion to change any time soon sadly.

Stephen

Josh Berry

unread,
Mar 25, 2011, 9:21:06 PM3/25/11
to java...@googlegroups.com
On Fri, Mar 25, 2011 at 10:57 AM, Reinier Zwitserloot
<rein...@gmail.com> wrote:
> How did I 'screw with quote trees'? All my quotations have been in order and
> from a single post. You did not elaborate on either
> InvocationTargetExceptions or InsufficientFundsException anywhere in your
> response, but you did ask me again to list examples. What did I miss?

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.

mP

unread,
Mar 25, 2011, 11:35:58 PM3/25/11
to java...@googlegroups.com
True my sample has many problems, but the same weakness is true of generics, where casting may be used to defeat a non wildcard generic type.

mP

unread,
Mar 25, 2011, 11:39:45 PM3/25/11
to java...@googlegroups.com, mP, phil swenson, Cédric Beust ♔
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 and try again, while uncheckness signifies its hard to handle so i wont.

Cédric Beust ♔

unread,
Mar 25, 2011, 11:54:53 PM3/25/11
to java...@googlegroups.com, mP, phil swenson
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 recover

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

 
, 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

No, it's broader than that: the point of checked exceptions is that you can do *something* about it, not necessarily limited to recovering.

--
Cédric


mP

unread,
Mar 26, 2011, 12:20:33 AM3/26/11
to java...@googlegroups.com, mP, phil swenson, Cédric Beust ♔


Sorry i was using recovery as a way to group possible actions to a problem- different word same desired outcome.


On Saturday, March 26, 2011 2:54:53 PM UTC+11, Cédric Beust ♔ wrote:


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 recover

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

Cédric Beust ♔

unread,
Mar 26, 2011, 12:35:32 AM3/26/11
to java...@googlegroups.com, mP, phil swenson
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 OOME

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.

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


Kevin Wright

unread,
Mar 26, 2011, 2:32:10 AM3/26/11
to java...@googlegroups.com, Cédric Beust ♔, mP, phil swenson


2011/3/26 Cédric Beust ♔ <ced...@beust.com>



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 OOME

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.

And no, it doesn't have checked exceptions (though it does have the regular variety)


 
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.

Cédric Beust ♔

unread,
Mar 26, 2011, 2:55:37 AM3/26/11
to Kevin Wright, java...@googlegroups.com, mP, phil swenson


On Fri, Mar 25, 2011 at 11:32 PM, Kevin Wright <kev.lee...@gmail.com> wrote:


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.

The last router with Erlang in it was shipped in 1998 and "Shortly thereafter, Erlang was banned within Ericsson Radio Systems for new products".

As for "Let it crash", Erlang helps very little with it since you are still in charge of creating and maintaining the chain of supervisors (in other words, no advantage on Erlang's part in this particular domain).

Having said that, would it be to too much to ask you to create a brand new thread when you respond to an email with a message that has absolutely nothing to do with the message you're quoting?

--
Cédric


Kevin Wright

unread,
Mar 26, 2011, 3:37:24 AM3/26/11
to Cédric Beust ♔, java...@googlegroups.com, mP, phil swenson


2011/3/26 Cédric Beust ♔ <ced...@beust.com>
Because I believe that the philosophy of allowing exceptions to naturally bubble up through a chain of supervisors, as opposed to forcing your caller to explicitly handle or rethrow is directly relevant to the discussion at hand.

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.  Again, directly relevant to the issue of such distinctions being embedded within Java's exception class hierarchy.


--
Cédric


Reinier Zwitserloot

unread,
Mar 26, 2011, 6:08:43 AM3/26/11
to java...@googlegroups.com, Josh Berry
On Saturday, March 26, 2011 2:21:06 AM UTC+1, Josh Berry wrote:

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 explained both the API in general terms and why such an API is quite unlikely to be observable publically (it's banking software, what do you think?). You call 'transferFunds' on someone's account, give it an amount and another account, and that's that. There is no return value, so encoding a problem via return value would be a fantastically silly design.

This is more than enough information for you to tell that this is a rare but valid example.


Josh Berry

unread,
Mar 26, 2011, 8:50:40 AM3/26/11
to java...@googlegroups.com
On Sat, Mar 26, 2011 at 6:08 AM, Reinier Zwitserloot <rein...@gmail.com> wrote:
> I explained both the API in general terms and why such an API is quite
> unlikely to be observable publically (it's banking software, what do you
> think?). You call 'transferFunds' on someone's account, give it an amount
> and another account, and that's that. There is no return value, so encoding
> a problem via return value would be a fantastically silly design.
> This is more than enough information for you to tell that this is a rare but
> valid example.
>

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.

Cédric Beust ♔

unread,
Mar 26, 2011, 10:39:39 AM3/26/11
to Kevin Wright, java...@googlegroups.com, mP, phil swenson


2011/3/26 Kevin Wright <kev.lee...@gmail.com>

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.

No, all Erlang proves is that you can write robust software with runtime exceptions. The question whether it's easier to do so with checked exceptions remains open.

--
Cédric


Reinier Zwitserloot

unread,
Mar 26, 2011, 12:13:41 PM3/26/11
to java...@googlegroups.com
On Saturday, March 26, 2011 1:50:40 PM UTC+1, Josh Berry wrote:

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.

Because I mean it. Given an API which as designed, returns void, but which needs to deal with errors (as I explained). Anybody that suggests the right way to return errors from this construct is by having a return value that needs to be inspected, especially if its banking stuff, is an idiot. I'll go to bat and defend my standpoint, but I doubt I have to. Are you honestly going to argue this?

TransferFunds could return any number of useful things, not the least
being a transferReceipt.

We have two options here:

(A) *OTHER THAN* whether or not the transfer caused an error, this transferReceipt class contains no guaranteed important information; all it really is, other than relaying errors, is a way to inspect some specifics about the transfer, such as the exact bank account numbers and such.

This is *HORRIBLE* design, as it becomes very very easy to forget to check for an error, at which point errors are just swallowed wholesale.

Alternatively, perhaps you mean:

(B) Error state is not the only crucial aspect of a transferReceipt; instead it contains vital information that e.g. needs to be written to the day's transaction receipt, or needs to be .confirm()ed or .apply()ed or some such.

If it needs to be confirmed or applied, then those methods need to throw a (checked would be better than unchecked) exception, and you just moved the problem around, you did not solve it. If it now needs to be logged, the design is even more screwed up, as you should do these things in a single transaction and the source that caused an action should highly preferably be the one to log it.


Either way I don't like this idea of returning a receipt with crucial information in it. Returning one with strictly non-crucial information in it is not just fine, it's a good idea. But errors are crucial and should this not be conveyed through it.
 

 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.


Sure, there are always scenarios where a seemingly appropriately checked exception ought to be bubbling up. That's kind of the point: If ALL checked exceptions should NEVER bubble then why use the exception mechanism to do it in the first place? The point is, there are many scenarios where just bubbling is not appropriate for this example, so the compiler forces you to acknowledge it. That's nice.

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.


So now you moved the goalposts yet again and have changed the argument to: Give me an example of proper usage of checked exceptions on void methods, for some system where it is not possible to envision an alternative API that is not obviously inferior which does not use checked exceptions.

I'm not playing this game.
 

Josh Berry

unread,
Mar 26, 2011, 2:46:38 PM3/26/11
to java...@googlegroups.com
On Sat, Mar 26, 2011 at 12:13 PM, Reinier Zwitserloot
<rein...@gmail.com> wrote:
> So now you moved the goalposts yet again and have changed the argument to:
> Give me an example of proper usage of checked exceptions on void methods,
> for some system where it is not possible to envision an alternative API that
> is not obviously inferior which does not use checked exceptions.
> I'm not playing this game.

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.

Neil Swingler

unread,
Mar 27, 2011, 7:19:29 AM3/27/11
to The Java Posse
Let's assume for the sake of argument that the pro checked exception
camp cannot convince the other side and vice versa. Let us also assume
that both groups are large enough that their views cannot be dismissed
by the other. The debate has gone on for 8 years or more so I cannot
see anybody changing their minds now.

Let's imagine that checked exceptions have been removed from the
language:
The pro checked exception camp can write exactly the same code as now.
The contra checked exception camp could write less code to achieve the
same effect as they do now. That must surely be a good thing.

I propose therefore that the positives of removing checked exceptions
would outweigh the negatives

- Neil
It is loading more messages.
0 new messages