Results: Should checked exceptions be eliminated from Java language? 

Voters
14 You may not vote on this poll

  • Definitely yes. They are a failed experiment.
    0%
  • Definitely not.
    10  71.43%
  • I can't decide.(I need more background info)
    0%
  • What is a checked exception??
    4  28.57%
    #1
  1. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Oct 2004
    Location
    Brussels
    Posts
    1,001
    Rep Power
    845

    Post Checked exceptions. To be or not to be?


    Should checked exceptions be eliminated from Java language?

    BACKGROUND
    I recently read a blog post claiming the checked exceptions are a failed experiment and should have never been introduced in the language.
    The debate is not new - it was launched 4 years ago by the Java advocate and author, Bruce Eckel. See for details the Bruce Eckel's articles Does Java need Checked Exceptions and Strong Typing vs Strong Testing, as well as his interview with the C# lead architect (taken also in 2003).

    For a while it appeared that the issue was settled (at least the dust was quietly settled down over it.. )
    But more recently Neal Gafter reignites the flame in his blog entry Removing Language Features?, counter-stroked by Elliote Rusty Harold in his call for Voting for Checked Exceptions

    I personally feel that checked exceptions are a good thing and should stay in the language.

    What do YOU think?

    Comments on this post

    • tfecw agrees
    • gimp agrees : Interesting
    • prometheuzz agrees
    "Problem" is just a bleak word for challenge. -- Richard Fish
    Javalanche
  2. #2
  3. Feelin' Groovy
    Devshed Supreme Being (6500+ posts)

    Join Date
    Aug 2001
    Location
    Chicago, IL
    Posts
    10,131
    Rep Power
    5058
    What do YOU think?
    I need an "I don't care" option.

    I mean, not to sound dispassionate, but this isn't an issue I'm terribly up in arms about. Whichever way it shakes out, I'll be fine, but I frankly don't see checked exceptions going away any time soon.

    ~
    Yawmark
    class Sig{public static void main(String...args){\u0066or(int
    \u0020$:"vÌÈÊ\"¤¾Àʲ¬Æ\"v¤Î¤\"²¤¨¸¬Æ".to\u0043h\u0061rArray()
    )System./*goto/*$/%\u0126//^\u002A\u002Fout.print((char)(($>>
    +(~'"'&'#'))+('<'>>('\\'/'.')/\u002Array.const(~1)\*\u002F)));}}
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Nov 2004
    Location
    Washington DC
    Posts
    2,755
    Rep Power
    1576
    Awesome poll, but I don't see the option to vote for my favorite IDE

    Removing anything from java isn't going to happen which is why i voted no. I would feel sorry for the guys who would have to go in and hack java apart to make sure the every existing java application for the past 12 years would have a chance to actually use that version of java.

    That said, I originally started deep in the checked exceptions camp and as time has passes I'm slowly moving to the unchecked camp. I'm not quite with Bruce Eckel and the never use checked exceptions folks, but i do disagree with Point 40 ( Use checked exceptions for recoverable conditions and run-time exceptions for programming errors
    ) in Effective Java as a hard fast 'exceptions rule.' It’s one that has almost become mantra like. When I talk about exceptions with some java programmers I can almost see their eyes glaze over as they chant ‘Use checked exceptions for recoverable…’

    As a side note, i think it's interesting that the Spring Framework has a lot of code devoted to turning checked exceptions into unchecked exceptions.

    Here's another link:
    Java theory and practice: The exceptions debate
    I've been meaning to follow up on Rod Johnson's views (summed up in the previous article) on the debate since they seem more in line with my thinking.

    Comments on this post

    • AP_programmer agrees : Yes we should have a poll for our favorite IDE
    • gimp agrees : "The answer to the question is: eclipse!"
    Open for extension, closed for modification
  6. #4
  7. <- My daily commute :^)
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Mar 2005
    Location
    Earth. Welcome.
    Posts
    1,500
    Rep Power
    1703
    I voted "Definitely not" for pretty much the same reasons as tfecw. I suppose it might be possible to tweak the inheritance of checked exceptions such that forced checks go away, but I sort of doubt it. I would think though that the types of changes necessary would cause many problems - not that I know that of course.

    I've read several opinions about checked versus unchecked exceptions. My personal policy is to never let a checked exception leak out of an API layer under any circumstances. For example, you would never receive an SQLException from a DAO in my code - regardless of your query. Instead I would either return an empty list, null, or if the query really needed to explode - maybe an IllegalArgumentException or IllegalStateException.

    One thing that I would like to see is a shortcut for saying "I'm not handling any exceptions here" - perhaps something like "rethrows" or "throwsall". For times when a library throws an exception, and I'm going to handle it one or two methods up. E.g., suppose I'm asking for a file name - I might actually try to open the file in a sub method, but want to handle the exception in the method that gets the file name. Something like this:

    Code:
    public void askForFile() {
        ... ask for file name
        try {
            processStuff( fileName );
        } catch ( AllSortsOfExceptions e ) {
            ... handle exceptions
        }
    }
    
    private void processStuff( String fileName ) rethrows {
        List stuff = getStuffFromFileName( fileName );
        ... process stuff
    }
    
    private List getStuffFromFileName( String fileName ) rethrows {
        ... actually open the file and get "stuff"
    }
    I realize one can allow an IDE to add all the "throws" clauses. But IMO it just adds unnecessary clutter in instances such as above.

    [EDIT I said the first paragraph badly. What I meant was that perhaps the folks at Sun could figure out some way to tweak things such that all the code everyone has written will not have any problems at all - perhaps through a tweak in the inheritance chain or something like that - but I wouldn't think so.

    Comments on this post

    • gimp agrees
    Last edited by mrider; June 6th, 2007 at 10:17 AM.
    A -> B: Ride.
  8. #5
  9. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Oct 2004
    Location
    Brussels
    Posts
    1,001
    Rep Power
    845

    Exclamation


    Originally Posted by tfecw

    That said, I originally started deep in the checked exceptions camp and as time has passes I'm slowly moving to the unchecked camp. I'm not quite with Bruce Eckel and the never use checked exceptions folks, but i do disagree with Point 40 ( Use checked exceptions for recoverable conditions and run-time exceptions for programming errors
    ) in Effective Java as a hard fast 'exceptions rule.' It’s one that has almost become mantra like. When I talk about exceptions with some java programmers I can almost see their eyes glaze over as they chant ‘Use checked exceptions for recoverable…’

    As a side note, i think it's interesting that the Spring Framework has a lot of code devoted to turning checked exceptions into unchecked exceptions.

    Here's another link:
    Java theory and practice: The exceptions debate
    I've been meaning to follow up on Rod Johnson's views (summed up in the previous article) on the debate since they seem more in line with my thinking.
    After the initial submission I realized that I should have added more links to "pro" opinions.
    Effective Java Exceptions is a good example. Although the author don't advocate specifically the use of checked exceptions, he presents the cases when we should use them.

    The classification of [abnormal] "conditions" in "contingencies" and "faults" looks to me quite arbitrary, but nonetheless useful for the purposes of the article.
    "Problem" is just a bleak word for challenge. -- Richard Fish
    Javalanche
  10. #6
  11. Contributing User
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Oct 2004
    Location
    Brussels
    Posts
    1,001
    Rep Power
    845

    Arrow


    This thread deserves more attention that it had received so far.
    So I thought that a nice summary of pros and cons from Voting for Checked Exceptions would be nice (especially for those of you who were too lazy to read the provided resources).

    PROS

    1. Checked exceptions convey useful information at compile-time

      Originally Posted by Elliote Rusty Harold
      "In brief, checked exceptions are for unpredictable environmental conditions such as I/O errors and and XML well-formedness violations while unchecked exceptions are for program failures that should be caught during testing, such as array index out of bounds or null pointers. A checked exception usually cannot be avoided by changing your code while an unchecked exception usually can be. That is, an unchecked exception normally indicates a bug in your program, and a checked exception doesn’t. That’s why we have to catch or declare checked exceptions and not runtime exceptions. A runtime exception will usually occur every time the code takes a particular path, whereas a checked exception may occur some times when a program runs through a path and not others, because checked exceptions depend on environmental conditions outside the program’s direct control. Therefore a problem that causes a runtime exception should be detected and fixed during testing, whereas a checked exception may well only appear in a customer environment. "
      While well-intended, ERH got it wrong (that reminds me of that saying, even the brightest people make silly mistakes). Checked exceptions are not for unpredictable environmental conditions, but for expected conditions; moreover, they are part of the API design/contract. They are part of the "business domain", E.g. if your business is working with files/streams, expect IOExceptions to occur; if you're working with RDBMSes, expect SQLExceptions to occur. Those are capturing the fact that you're interacting with a specific abstraction layer.
    2. Not having them makes really hard to properly handle the "unexpected" (at the right layer)

      Originally Posted by Ben Engber
      In languages without checked exceptions it is often _impossible_ to know how to handle an expected exception. For example, let’s say I want to make a call to a web service in C#. Nothing fancy. Just a simple method call. This is a place where I should expect certain types of failure conditions and handle them gracefully. So what should I catch? Trial and error shows that all kinds of exceptions might be thrown here: XmlExceptions, IOExceptions, InvalidOperationExceptions, etc. These cannot possibly be listed in the API documentation, since the underlying implementation can throw whatever exceptions it likes. The only course of action I can take would be catching ALL exceptions. But then I might swallow real unexpected problems that ought to be propagated up.
    3. Better handling; easy refactoring in IDEs
      Originally Posted by Scott Ellsworth
      Checked exceptions are really quite useful, in my experience, as there are plenty of cases where the best person to handle a failure is some level up the call chain. Using judicious checked exceptions makes that fairly easy to do.
      Both eclipse and idea make it pretty easy to add the appropriate throws clause, and you really should not care that much _who_ threw the exception unless you intend to handle it. Frankly, even then, I find that I can usually do the right thing without knowing much about who threw the exception.
      Originally Posted by D'Arcy
      1) RuntimeExceptions ALWAYS indicate bugs in the code,
      2) Errors ALWAYS indicate things your program should not try to deal with (save certain types of apps)
      3) All checked exceptions ALWAYS indicate things that need to be handled in some way (shut down the app, log a message, report to the user).
      So a properly functioning program should NEVER throw a RuntimeException as it indicates a bug, and if it is a properly functioning system it should not have bugs. If you start putting things like failure to connect to a database under the category of bugs the whole model breaks down.
    4. Usability; code maintenance; educational coders must knowingly decide to either catch or re-throw.
      Originally Posted by Alastair Rae
      Ever programmed a large C system? Nearly every other line is error handling. Oh for an exception mechanism.
      Ever programmed a large C++ system? Everybody throws std::runtime_error as soon as something goes wrong; nobody declares anything and the you end up with core dumps and no explanation.
      Ever programmed a large Java system? Methods declare exceptions and callers have to decide what to do - catch or declare. Having to decide is a good thing and the compiler enforces it so lazy programmers have to decide.


    CONS

    1. Checked exceptions are pointless since the caller doesn't know how to properly handle the exception anyway.
      Originally Posted by Ravi Venkataraman
      When a database is down, the most meaningful thing that can be done is to inform the user and exit the application (Unless an alternative data source is available, or if the data from the database is not really required.)
      If this is written as a checked exception, then all the way up the call stack one must throw this exception in the method declaration, leading to code bloat; or one must handle it immediately and then exit.
      Throwing a RuntimeException in this case makes sense because any caller up the stack can handle this if it knows what to do; or else simply pass it back up the stack until one quits the application. Checked exception here gives no benefit except to the consultant who write bloated code or gets paid by the number of lines of code/time spent.
      [...] Even in Java, you can sub-class RunTime Exceptions and catch them. Using them avoids the requirement to declare the Exception thrown in a method,and then have each caller (all the way up to the point of entry into the system) either catch the Exception or declare it in a throws clause. Using RuntimeException, only the method that knows what must be done will need to catch it. The rest can be blissfully ignorant of it, primarily because they can do nothing even if they know of the Exception, they can merely pass it on.

      It is much simpler to develop applications with very few checked exceptions. They are more robust, in my experience, than the false sense of security offered by checked exceptions. That is why no other language has checked exceptions, and there is no request for its inclusion from any other programming language community.
    2. Sometimes is difficult (as an API designer) to choose checked vs un-checked. Checked exceptions are complex & difficult to learn (their proper usage). They are more of a hassle than help.
      Originally Posted by Adrian Baker
      One difficulty is that this environmental versus programmatic distinction often depends on the particular invocation of a method, whereas the checked vs unchecked decision is hard-coded in the library when it’s written. For example, parsing xml which I’ve just serialized using JAXB would be a programmatic error if it fails, so would compiling an XPath expression which is held in a static String. Checked exceptions in these case are a bit of a pain. But in cases where the xml is genuinely 'unknown' (eg a user uploads an xml file), the checked exception is appropriate: same method, different uses.
      Elliotte, you often argue against features on the grounds that they are complex/difficult to learn/difficult to use properly. Would you agree that even though the checked vs unchecked distinction is useful, that it can be a difficult one to make & that very often it’s not made correctly in APIs? If parts of even the Java API don’t get it right then perhaps it’s a sign that this is a feature that causes more hassle that it solves.
      [..] There’s a valid argument to be made that try/catch blocks clutter code.
    3. The library designer oftentimes cannot foresee all the ways a client will handle the exceptions. Then why to force him to add throws clauses or try-catch blocks??
      Originally Posted by Hallvard Trætteberg
      There are many ways of formulating the problem, the most interesting one (IMO) is 'why do you think you know better than me that this is something that has to be handled (caught or redeclared)'.
      Declaring an exception (whether unchecked or checked) is not the problem, it’s that it’s usually impossible for an API developer to know in what cases the exception is so important that it must be considered (caught or redeclared) by the direct caller. Rules of the kind 'use checked exceptions when the problem is in the environment' or 'use checked exceptions when the caller should know how to handle it' confuses forcing with declaring, it should be 'declare the exception using throws when …'.
    4. Adding many checked exceptions to an abstraction forces you to add a terse DomainException on top of them; this in turn forces the callers to catch a meaningless exception.
      Originally Posted by Kjetil Valstadsve
      Provided you do checked exceptions, what you usually do with the SQLException is wrap it in an exception type belonging to the domain model layer. This could be a very specific type of exception, or a very general DomainModelException or something. But even if you make very specific exception types, you end up with a lot of them, and eventually you create the DomainModelException superclass, instead of having long throws lists in many methods. Then, as you add error handling (by throwing exceptions - you want the code to be robust right?) in the domain model layer, you will eventually find that all method signatures in the domain model layer declare “throws DomainModelException”.
      And by this time, the “throws DomainModelException” declaration tells you nothing!
      You have no meaningful information about actual error causes at compile-time, just a lot of declarations AND an enormous amount of catch (DomainModelException e) in the layer above you! You might just as well have used unchecked exceptions, that would have done the same job with less and simpler code. When your app does fail, you end up with an enormous nested exception to log (or present to the user), and have you noticed how only the innermost cause can tell you what happened? Usually “Connection refused” or something. All that you really needed was to get THIS one exception propagated to the application-level error handler - did you really need all the wrappers?
    5. Designing or using APIs with checked exceptions encourages improper uses of exception handling mechanism -adding throws Throwable or Exception in method signatures, try-catch blocks with empty catch etc.
      Originally Posted by Tarun Ramakrishna Elankath
      Kjetil Valstadsve - you are the _ONLY_ non-emotional commenter on this site that has offered a clear, rational and detailed explanation about why checked exceptions are harmful. Not the productivity claim, not the code bloat claim - though checked exceptions indeed cause bloated code , but the correct statement - they simply break OO and are harmful for software design in the long term. The most hated checked exception in this category is the java.rmi.RemoteException - I hated it from the very first day I knew RMI (Kept saying to myself - OMG this breaks OO - I cannot believe that the designers actually thought this was a bright idea).
      Propagating low-level exception types by declaring them in the throws clause of all client interfaces (the solution that ERH recommends) is a VERY, VERY, VERY bad practice that completely destroys one of the primary principles of object oriented programming - decoupling of contracts and implementation.
      Kjetil has already described the problem well, but let me add my 2 cents. If I create an interface, for example say ‘Paginator’ which paginates rows, I DO NOT want to declare an SQLException in the getNextPage() menthod if the db implementation of this Paginator fails. Why? because in using that horrible declare clause you have coupled my Paginator interface with its db-specific implementation. In the future (or in unit testing) if I want to provide use an in-memory, local Paginator, that implementation will also need to declare that completely useless exception.
      What do the group of checked-exceptions proponents who are also OO purists advocate to solve this problem? Oh..you simply wrap up the underlying exception..in your case the SQLException in a PaginatorException class and declare that instead. So basically everything starts looking like this
      java Code:
      public interface Paginator {
      List getNextPage() throws PaginatorException
      List getPrevPage() throws PaginatorException
      …. throws PaginatorException
      }

      (Note: OO purists please don’t complain about the non-generified List return type there - this is an example)
      So now we have all our caller-code in the next layer which uses Paginator (assume its code that paginates over Product listings) to do this:
      java Code:
      try {
      List productListing = paginator.getNextPage();
      } catch (PaginatorException e) {
      throw new ProductListingException(e);
      }

      This is quite silly IMHO - it may be more OO but you have lots of boilerplate code doing nothing but wrapping and re-throwing exceptions. And you have that brain-washing ‘throws LayerException’ text in every method signature. That wrapping code takes CPU time and these deeply nested exceptions objects cost memory which can be better utilized elsewhere.
      I would rather use unchecked exceptions and propagate them to the top error-message display code. _IF_ the error-handling logic code has insufficient contextual information to determine which error message should be displayed, ONLY THEN would I introduce a new LayerRuntimeException class that would wrap the underlying fault, add some context data and re-throw it. The advantage of using this versus a LayerCheckedException is that it does _not_ force every layer above me to create a brain-washed-possibly-do-nothing-but-just-sitting-there LayerAboveCheckedException or alternatively declare a ‘throws LayerBelowCheckedException’ in the LayerAbove interface method signatures (which completely breaks OO).
      Very powerful, almost convinced me.
      The argument of improper usage is probably the most compelling "don't do it" argument.
      Unfortunately, this is often the case - too many libraries are poorly designed and overuse or misuse checked exceptions, making hard for regular coders to use their APIs.


    Now everybody vote!
    Make this poll a success!

    P.S. "Don't care" is unconceivable Yawmark

    Comments on this post

    • Nemi agrees : Great summary!!
    "Problem" is just a bleak word for challenge. -- Richard Fish
    Javalanche
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2006
    Posts
    173
    Rep Power
    73
    > Now everybody vote!
    Aww..how could I disagree with you. Yes the answer is 'definitely not'.

    There are a lot of people out there complaining about Java is this and Java is that. Compulsory handling of checked exceptions, adds to their fun. The exception model of C++ still is my favorite.

IMN logo majestic logo threadwatch logo seochat tools logo