Topic
IC4NOTICE: developerWorks Community will be offline May 29-30, 2015 while we upgrade to the latest version of IBM Connections. For more information, read our upgrade FAQ.
16 replies Latest Post - ‏2012-11-14T22:10:11Z by SystemAdmin
SystemAdmin
SystemAdmin
757 Posts
ACCEPTED ANSWER

Pinned topic Checked vs. Unchecked Exceptions

‏2004-06-01T23:38:59Z |
Many of the arguments I've seen/heard against checked exceptions revolves around developers abusing them (catching Exception or Throwable instead of a specific type, throwing every Exception your method may encounter without abstrascting them, etc.). To me, those are not problems with checked exceptions, but problems with poor programmers.

Even if all exceptions were unchecked, such poor programmers could still catch Throwable when they determine their code is blowing up. And making all exceptions unchecked doesn't force them to abstract their exceptions. Instead, you're left with the same problem as before -- throwing all exceptions you encounter -- except now it's invisible.
Updated on 2012-11-14T22:10:11Z at 2012-11-14T22:10:11Z by SystemAdmin
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Checked vs. Unchecked Exceptions

    ‏2004-06-07T23:11:56Z  in response to SystemAdmin
    I agree with the previous post that most of the problems are not checked vs. unchecked but lazy programming and unchecked exception make this problem worse not better.

    My own advice is to list the unchecked exceptions in the throws clause so that they are clearly documented, including Javadocs. Also I see nothing wrong with catching a series of exceptions and throwing a more sensible exception even if this involves catching 6 exceptions (as the original article gave as an example).

    The original article gave some code from Bruce Eckels (and I think Heinz Kabutz was a joint author of this) that converts a checked exception into an unchecked exception. This code is now obsolute since Java 1.4. All exceptions now have a 'caused by' message and this is the prefered mechanism for converting one exception into another.

    I think the best advice on the subject and it is the advice that I follow is Joshua Blochs advice that you use checked exceptions when the user (programmer) of the method can reasonably be expected to deal with the exception, if the user is unlikely to be able to do deal with the exception then use an unchecked exception.

    Note that JB is not advocating just passing unchecked exception through, he is advocating passing on a sensible exception. IE catching and converting.
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Checked vs. Unchecked Exceptions

    ‏2004-06-09T00:47:04Z  in response to SystemAdmin
    I must admit that I dislike checked exceptions for one (well documented) reason: they can cause horrendous ripple effects when you have to add a new checked exception to a low-level method that is (indirectly) used by a large part of a system. In my experience this significantly complicates even simple refactorings, plus I don't believe in crystal ball gazing (ie. the ability for someone to correctly predict, 100% of the time, exactly which exceptions a given method should throw). And no it's not about avoiding design up front, it's about the simple fact that the systems we so carefully design and implement inevitably get torqued and twisted into unrecognised shapes by unexpected changes in requirements later in the piece. That's just reality.

    Anyway, it seems to me that one of the primary benefits of checked exceptions is that they appear in the Javadoc for the method, so a user of that method can always easily find out which exceptions could possibly be thrown out of it (and handle them appropriately, if they so choose). I've always wondered whether it would be possible / practical for javadoc (probably with some help from javac) to automatically determine the full set of thrown exceptions for a method, and automatically add that information to the Javadoc for the method. This gives the best of both worlds, by allowing developers to throw whatever exceptions they like without having to list them, while also giving users of a method the ability to easily determine which exceptions a particular method throws (and handle them appropriately, if they so choose).

    There's a good chance that I don't fully comprehend the complexity of transivitely determining all possible thrown exceptions for a given method, of course, but it seems like a reasonable compromise to me.
    • SystemAdmin
      SystemAdmin
      757 Posts
      ACCEPTED ANSWER

      Re: Checked vs. Unchecked Exceptions

      ‏2004-06-09T01:07:41Z  in response to SystemAdmin
      I sympathize with pmonks, it is a pain to update method signatures (whether checked exceptions, arguments, or return types). But as pmonks said it does happen, on the bright side the compiler does tell you of these mistakes. So in a way checked exceptions are good, you can't forget to change classes that use the method (they may sinply pass the exception up the chain).

      With regard to Javadoc listing all exceptions for you, that would be nice. I use a technique that achives this, I list all the exceptions including unchecked, then my formatter (jalopy) automatically adds them to the Javadoc.

      An observation on the checked vs. unchecked exceptions debate, I notice that people who like unchecked exceptions generally like scripting languages also, e.g. Bruce Eckel's favourite language is python. I am not that keen on scripting languages, but I do use them, so I guess that is why I have no problem with checked exceptions, to me they are just extra type checking.

      I find Joshua Bloch's advice "to use checked when the user can reasonably be expected to deal with the problem and unchecked otherwise" the best guide. Sometimes the standard library does not follow this advice, e.g. it throws an IOException in many circumstances that the programmer can't do anything about and the program needs to terminate because there is some major problem like no disc space left or the operating system has thrown a wobbly.
    • SystemAdmin
      SystemAdmin
      757 Posts
      ACCEPTED ANSWER

      Re: Checked vs. Unchecked Exceptions

      ‏2004-06-14T00:32:47Z  in response to SystemAdmin
      This issue was addressed in the article and in Bloch's book -- methods should throw exceptions that are appropriate to their abstraction level, not their implementation. Proper creation of exception abstractions will greatly reduce the occurence of this. Lazily propagating everything thrown by the implementation will not.

      It would be nice if Javadoc did as you suggest, but its far from a comprehensive solution, because Java classes can be substituted at runtime. When X calls Y, just because this implementation of Y throws runtime exceptions YE1 and YE2, the compiler can't make any assumptions about which version of Y will be called at runtime. So you lose everything but that which the compiler can prove is thrown in the class being analyzed, which is limited to the runtime exceptions directly thrown by its implementation.
      • SystemAdmin
        SystemAdmin
        757 Posts
        ACCEPTED ANSWER

        Re: Checked vs. Unchecked Exceptions

        ‏2004-06-14T17:44:57Z  in response to SystemAdmin
        I think abstract exceptions help, but they still have a number of problems, including:
        1. you end up writing boatloads of "wrap exception in abstract exception" code
        2. you still need to predict ahead of time what all of your abstract exceptions will be

        Point #2 is the kicker for me - I try not to rely on development patterns or practices that require me to predict the future, since funnily enough my accuracy in predicting the future isn't that great. ;-)

        And you're right that Javadoc is unable to do what I suggest today due to runtime classloading - that's why I said "probably with some help from javac". If javac automatically decorated method signatures in .class files with the list of exceptions the method throws, that might cover some cases.
        • SystemAdmin
          SystemAdmin
          757 Posts
          ACCEPTED ANSWER

          Re: Checked vs. Unchecked Exceptions

          ‏2004-06-22T07:20:00Z  in response to SystemAdmin
          > I think abstract exceptions help, but they still have
          > a number of problems, including:
          > 1. you end up writing boatloads of "wrap exception in
          > abstract exception" code
          > 2. you still need to predict ahead of time what all
          > of your abstract exceptions will be
          >
          > Point #2 is the kicker for me - I try not to rely on
          > development patterns or practices that require me to
          > predict the future, since funnily enough my accuracy
          > in predicting the future isn't that great. ;-)

          IMHO the way to go is to define exceptions on a per module / package basis. I would not try to define as abstract checked exceptions as IllegalStateException and others. Rather define all the exceptions that a module / package can reasonably throw and use them for wrapping.

          Btw: Sun did a really bad job in defining exceptions for JDBC. IMHO they should at least have differenciated connection errors, data errors, authentication errors, SQL sytax errors etc.

          Regards

          robert
    • SystemAdmin
      SystemAdmin
      757 Posts
      ACCEPTED ANSWER

      Re: Checked vs. Unchecked Exceptions

      ‏2004-06-14T16:28:13Z  in response to SystemAdmin
      I beg to (partly) differ...

      > I must admit that I dislike checked exceptions for
      > one (well documented) reason: they can cause
      > horrendous ripple effects when you have to add a new
      > checked exception to a low-level method that is
      > (indirectly) used by a large part of a system. In my
      > experience this significantly complicates even simple
      > refactorings, plus I don't believe in crystal ball
      > gazing (ie. the ability for someone to correctly
      > predict, 100% of the time, exactly which exceptions a
      > given method should throw).

      There is a simple rule with checked exceptions: if your module used other modules behind the scenes (say a general persistence layer using JDBC without making it public) you should wrap exceptions. In that case, they won't ripple up this module if Sun decided to add another exception type to JDBC (just an example).

      Of course it's more difficult if the module relied on is visible at the interface of your module. In that case you might see ripple. But generally speaking (in an ideal world), modules should always depend on more mature (and thus stable modules). That way interface changes (like added exceptions) in lower level modules are rather unlikely.

      Yuo can't avoid rippling up in every case, but you can do a great deal about it to minimize effects.

      > And no it's not about
      > avoiding design up front, it's about the simple fact
      > that the systems we so carefully design and implement
      > inevitably get torqued and twisted into unrecognised
      > shapes by unexpected changes in requirements later in
      > the piece. That's just reality.

      Yes, very true.

      > Anyway, it seems to me that one of the primary
      > benefits of checked exceptions is that they appear in
      > the Javadoc for the method, so a user of that method
      > can always easily find out which exceptions could
      > possibly be thrown out of it (and handle them
      > appropriately, if they so choose).

      You can include unchecked exceptions here as well. The stdlib JavaDoc does it all over the place.

      > I've always
      > wondered whether it would be possible / practical for
      > javadoc (probably with some help from javac) to
      > automatically determine the full set of thrown
      > exceptions for a method, and automatically add that
      > information to the Javadoc for the method.

      It's not possible to reliably generate this set of exceptions since not all classes might be available when javadoc is run.

      > This
      > gives the best of both worlds, by allowing developers
      > to throw whatever exceptions they like without having
      > to list them, while also giving users of a method the
      > ability to easily determine which exceptions a
      > particular method throws (and handle them
      > appropriately, if they so choose).

      Ideally, yes. But you can do it manually (see above).

      > There's a good chance that I don't fully comprehend
      > the complexity of transivitely determining all
      > possible thrown exceptions for a given method, of
      > course, but it seems like a reasonable compromise to
      > me.

      If it could work. I think it's not worthwile the effort since there are too many cases where it would not work reliably plus it's quite an effort. javadoc is quite slow already, I wouldn't want more time added to that.

      Regards

      robert
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Checked vs. Unchecked Exceptions

    ‏2004-06-14T00:29:25Z  in response to SystemAdmin
    I'm mostly in agreement (and I hope that was clear from the article) -- all of the examples you cite are departures from good, well-defined practices, not the mechanisms themselves. However, a number of intelligent people who think the same have observed that in the real world, exception handling ends up being one of the biggest problems in many applications because of widespread lack of conformance to good practice.

    There ARE some real problems with Java's exception hierarchy, such as the fact that RuntimeException extends Exception and therefore catch(Exception) will (generally accidentally) swallow unchecked exceptions too.

    But the underlying question that is worth exploring is: if X% of developers make Y mistake frequently, how big does X have to be before the language design bears part of the blame? (Think of your favorite criticisms of C/C++ -- a lot of them are probably in the camp of "makes it too easy to make XYZ mistake.")
    • SystemAdmin
      SystemAdmin
      757 Posts
      ACCEPTED ANSWER

      Re: Checked vs. Unchecked Exceptions

      ‏2004-06-14T16:32:19Z  in response to SystemAdmin
      > There ARE some real problems with Java's exception
      > hierarchy, such as the fact that RuntimeException
      > extends Exception and therefore catch(Exception) will
      > (generally accidentally) swallow unchecked exceptions
      > too.

      Yeah, or put differently, the problem is that there is no single root exception class for checked exceptions. Although from my experience this is not too big a problem since Eclipse generates catch clauses for all checked exceptions that can be thrown in a block. :-)

      > But the underlying question that is worth exploring
      > is: if X% of developers make Y mistake frequently,
      > how big does X have to be before the language design
      > bears part of the blame? (Think of your favorite
      > criticisms of C/C++ -- a lot of them are probably in
      > the camp of "makes it too easy to make XYZ mistake.")

      Interesting question. In this case it's not only the language but the standard library design and how that is related to certain language specs.

      Kind regards

      robert
    • SystemAdmin
      SystemAdmin
      757 Posts
      ACCEPTED ANSWER

      Re: Checked vs. Unchecked Exceptions

      ‏2004-06-15T03:35:53Z  in response to SystemAdmin
      > There ARE some real problems with Java's exception
      > hierarchy, such as the fact that RuntimeException
      > extends Exception and therefore catch(Exception) will
      > (generally accidentally) swallow unchecked exceptions
      > too.

      I agree that the hierarchy could be much improved and I will add that the naming is a problem. CheckedException and UncheckedException are better than Exception and RuntimeException respectively. Also RuntimeException is particularly bad since they all occur at runtime!

      > But the underlying question that is worth exploring
      > is: if X% of developers make Y mistake frequently,
      > how big does X have to be before the language design
      > bears part of the blame? (Think of your favorite
      > criticisms of C/C++ -- a lot of them are probably in
      > the camp of "makes it too easy to make XYZ mistake.")

      I again agree with your comments.

      What I disagree about is that the answer is to make all exceptions unchecked. I think this simply hides many of the problems, so yes it is easier to change code but you have simply introduced a bug that the poor user will be left to find. If something throws an exception then the program should deal with it, not abort.

      This discussion poses an interesting question: if a combination of checked and unchecked exceptions is still not ideal and unchecked on their own is worse, then what is better?
      • SystemAdmin
        SystemAdmin
        757 Posts
        ACCEPTED ANSWER

        Re: Checked vs. Unchecked Exceptions

        ‏2004-06-22T05:54:54Z  in response to SystemAdmin
        > What I disagree about is that the answer is to make all exceptions unchecked.

        I hope my article didn't suggest this! I think its a bad idea too.
        • SystemAdmin
          SystemAdmin
          757 Posts
          ACCEPTED ANSWER

          Re: Checked vs. Unchecked Exceptions

          ‏2007-01-02T19:54:32Z  in response to SystemAdmin
          > > What I disagree about is that the answer is to make
          > all exceptions unchecked.
          >
          > I hope my article didn't suggest this! I think its a
          > bad idea too.

          I know this thread has been asleep for over 2 years, so I'm sorry to wake it up... I have stumbled upon it accidentally, and couldn't resist posting my comment. Brian, I hope you have changed your mind since then. I'm sure you have... :) I have been programming for almost 20 years now. Since 2000, almost exclusively in Java. I am ashamed to admit that, in the beginning, like almost everyone else, I took checked exceptions for granted and didn't question their "benefits." Today, there is absolutely no doubt in my mind that checked exceptions were not only an ill-advised addtion to Java, they were probably the worst thing that has ever happened to the software industry. Let me explain. I have worked on many, many projects, large and small. Never have I seen error handling done correctly with checked exceptions. For the most part, Java developers treat error handling as an afterthought. It is something they do in response to the compiler's reminder that the code may throw an exception that must be handled. This results in error "handling" implementations that are incoherent, decentralized, obstructive, confusing, and... senseless! Worse than anything, it results in an obfuscation of the original errors and, often, impossibility to trace the defects. It also results in many errors NOT being caught at all. Developers often handle only what the compiler tells them to handle (usually, immediately at the source of the error, instead of where it should be handled properly) and let other (runtime) errors to slip by. Then, they complain about the "nasty" runtime exceptions that exist only to make life difficult. Somehow, we have forgotten that error handling is - and has always been - an essential part of software design. This task may not - and must not - be assigned to the compiler, IDE, or anything but the application's designers, i.e. the software architects and programmers. Unfortunately, too many "architects" today have never been good programmers in the first place, but sure they enjoyed going to the meetings and discussing "the big picture". So they worked hard to get promoted to architect positions with a higher salary, happily leaving the tedious work to the junior "code monkeys". So, often, there's no good architect to actually know the difference between the good and bad error handling. They just leave this "non-essential" task for the developer to figure out. And the developer has just graduated from an agricultural college with a degree in history of farming, but a recruiter offered him a $50/hour job (beats the heck of collecting unemployment...) So, there you go... Ok, ok, it's not always the case, but unfortunately, this happens in our industry way too often... :)

          In your article you express a concern that run-time exceptions are usally not very well documented, which prevents developers from knowing what to expect. I beg to differ with you regarding the very premise of that argument. Developers often ask me the question: "Now that the compiler doesn't tell me, how do I know which exception to handle?" This question reflects the most common misconception about error handling in software applications. The misconception that the Java authors should be held responsible for, in my opinion. Interestingly, in most cases, developers [i]do not need to know[/i] anything other than what is [i]stated in the business requirements.[/i] Everything else should be treated as "something bad that really wasn't meant to happen per design." This makes the general error handling strategy very simple! Here are the simple tasks that the developer/application designer must face when designing the high-level layout for the application:

          1. Determine the location for the top-level handler that will catch [i]all[/i] errors that bubble up to it from within the application. This is usually a "try/catch (Throwable t)/finally" construct around the process that implements the main task of your application or component/module.

          2. Get familiar with the business requirements (funny that I should mention that! :)) and single out the [i]legitimate use cases[/i] where an error should be caught and handled [i]before[/i] it reaches the above-mentioned top-level handler. Such handling will mean implementing an alternative action in response to the error. Such cases will be represent your [i]business[/i] errors. Note that since these errors are documented in [i]your own business requirements[/i], shame on you if you need the compiler to tell you about them! ;) You must [i]design[/i] for these alternative actions. You don't need to know the implementation details of the API that throws the error. Even if the API is written by you, in most such cases you can treat it as a black box from the standpoint of its client - when handling the failure inside that black box. All you need to know that your particular business operation failed, and your application knows what to do in this case. So, in most cases, you just need to catch all possible exceptions in that API and redirect your process accordingly. In rare cases, yes, you might have to investigate the API a bit deeper to look for a more specific exception type. For example, you may want to distinguish the Spring's DataRetrievalFailureException from a NullPointerException. The former indicates that your data was not retrieved from the database, the latter indicates something totally unacceptable that has nothing to do with the business case. But such details are easy to uncover - if you look for them when following nothing but your business requirements. What developers must remember is that they absolutely must [i]design[/i] for error handling. Instead, most Java programmers today thoughtlessly catch just about anything that the compiler points at, put wrappers around wrappers, re-throw useless exceptions but chop-off valuable stack traces, log the same error dozens of times at each step in the call stack, etc.

          What makes things even easier for those who want to do it right is that, in practice, most applications have very few cases of the [i]distinct[/i] legitimate "business" cases mentioned in step 2.

          3. Ensure that each error propagates [i]freely[/i] from the source of the error to the [i]only[/i] dedicated handler that is [i]designed[/i] to handle it, the handler that has the sufficient application context to handle the error properly. Under no circumstances, the error should be caught and tinkered with before it reaches that handler.
          Run-time exceptions were designed to ensure just that. Checked exceptions sounded like a good idea (and so did Communism to some people, but look at the results of all the implementation attempts! :)) ) In reality, they introduce unimaginable chaos into Java programs. Most tragically, they have corrupted the mentality of several generations of software engineers (especially those who, prior to Java, have not seriously programmed in any other language that uses exceptions.) People now do not put much thinking into error handling. Instead, they take a simple task and make a total mess out of it. I often find myself refactoring someone else's implementations and end up with just a few lines of useful code after throwing away literally hundreds and, sometemes, thousands of lines! People write tons of code to handle and throw their checked exceptions, and then write more code to overcome the obstacles ctreated by those exceptions. It becomes a chain reaction. A simple task now turns into an unmanagable pile of spaghetti code.

          Brian, you are absolutely correct mentioning the point that if so many people make certain mistakes so consistently then, perhaps, there is a flaw in the core approach itself. The problem with checked exceptions is that it is absolutely unrealistic to even hope to be able to control their correct usage via code reviews, etc. They create way more trouble than the tiny benefit they bring in simple situations when the call stack is guaranteed to have only the caller and a single callee. Sadly, so many people blindly follow those who have introduced the dogma, and don't even try to open their eyes and see how easy it is to program w/o checked exceptions. I have been doing it for years now, and I've never looked back. It helps me keep my code clear and simple, reliably catch [i]all[/i] errors and handle them in centralized locations. I never have to guess what happened when an exception occurs. My log files contain all the information I need to instantly identify and isolate the problem. Life is much, much easier without checked exceptions.

          Also, to answer your quote at the top of this posing... Mixing checked and unchecked exceptions is a [i]bad[/i] idea. First of all, we must realize that, generally, each checked exception is only a [i]subset[/i] of all possible errors. That means, handling the specific checked exception in response to the compiler's complaint is [i]never[/i] enough. If you stop there, you are guaranteed to miss something that will blow up your application. (I sure hope NASA engineers do not rely on checked exceptions!) Therefore, you still have to do everything I described above in 1 and 2, except your code is now polluted with tons of specific (most certainly, unnecessary) handlers that may interrupt an essential exception on its way to the one and only correct handler, which inevitably results in the loss of error information. That's something that happens on every project that I see in my consulting business. It's already 2007, years have passed after some brightes people in the industry started speaking against checked exceptions. No language designers followed Java's suit. The best Java applications and frameworks today do not use checked exceptions. Spring, Hibernate... And yet, countless numbers of incompetent Java developers thoughtessly use checked exceptions to this day. They post angry comments in Java forums stating that runtime exceptions cause all the troubles in Java, that they wish all exception were checked, etc. Well, that brings us to the other side of it. If we can't reliably mix RT and checked exceptions, and we don't like RT exceptions, can we indeed make all exceptions checked? The answer is, most certainly, NO. There is a reason why the authors of Java didn't do that in the first place. They just couldn't. That would have made the language totally unusable. Every method would have to declare countless exceptions in its signature, and every method would have to deal with the countless checked exceptions thown by the code inside. With no benefit. Anyone who still doesn't understand it is just not competent enough to be a programmer, or still has a long way to go and learn...

          The conclusion is simple. If you can't mix RT and checked exceptions reliably, if you can't exclusively use only checked exceptions, the only solution is: use RT exceptions only, and, for God's sake, design your code according to the business requirements, don't improvise based on the compiler's messages! Start with a global catch-all handler, and then implement a few specifc strategically placed "business" handlers. Everything that is not caught by these business handlers should freely go all the way to the top-level handler where the full stack trace will be logged and the predefined (per design) generic action will be performed for any critical error. That's it. Now, concentrate on you business logic and don't bother with useless exception handling every step of thye way.

          Gosling once published an article defendnig checked exceptions where he claimed that they remind the programmer that something may potentially not work within the method... Excuse me? Is he serious? Shouldn't someone with a degree in Computer Science have just enough brain cells to assume that, potentially, something may not [i]always[/i] work the way it's meant to - in a piece of software??? Any software? Any method? Isn't that what any junior programmer [i]must[/i] know and understand even before they even have written their first line of code? Do we need a compiler to remind us that the Earth is round? Or was Gosling talking to the thousands of "accidental programmers" with degrees in accounting, history, or whatever, who have flooded the industry since the 90's and continue to arrive, attracted by more or less decent salaries?

          I am confident: there is no future for checked exceptions. At least, in the way Java implements the concept. I have mentioned Spring, Hibernate... Now, look at Sun's EJB3!!! Wow! No checked exceptions there! A good sign. But how many "average" programmers have noticed? Not many. Unfortunately, it will take a formal announcement from the folks at Sun admitting their terrible mistake, etc., to start slowly converting the "masses". Sadly, no matter how many bright (and brightest) people in the industry have spoken against checked exceptions (Rod Johnson, Bruce Eckel, Anders Hejlsberg, to name a few), it has had almost no impact on "the people in the trenches." When I visit client sites I often meet Java "programmers" with "many years of experience" who have never even heard the terms "checked" and/or "runtime". Sad...

          Sorry for the long rant, and hope I am not re-starting a religious war... The comment has almost turned into a white paper. :)

          Cheers,
          Consatntine
          • SystemAdmin
            SystemAdmin
            757 Posts
            ACCEPTED ANSWER

            Re: Checked vs. Unchecked Exceptions

            ‏2007-03-23T22:45:47Z  in response to SystemAdmin
            I agree with you Constantine. Having the compiler checking exceptions leads in too many cases to code such as this:

            void foo()
            {
            try
            {
            // initial code
            // place where exception is thrown and checked by compiler
            // some more code
            }
            catch(Exception e) {}
            }

            The problem is that "some more code" will not get executed and the flow continues leading to some mysterious result in some other part of the code base that relied on "some more code" getting executed.

            If there was no checking, the developer would not have put in the try/catch with no body.

            There also the pattern (encouraged by some in the name of some "best practices") to do this in the catch:

            catch(Exception e)
            {
            throw new FooException("didn't work");
            }

            which now the client of the foo() method looses the fact of where in foo() the problem occurred (line number), and has to resort to debugger or println tracing.

            If the compiler didn't check exceptions, there would be much fewer problems such as these.

            To get around these kinds of issues, I have to resort to the following:
            void foo()
            {
            try
            {
            // initial code
            // place where exception is thrown and checked by compiler
            // some more code
            }
            catch(Exception e)
            {
            throw new RuntimeException(e);
            }
            }

            Which at least will show where the problem occurred in the root cause of the runtime exception at the base handler.

            From practical experience, there are very few places where we need to handle exceptions.. maybe in a main or in a wrapper around AbstractAction that all other actions extend. Also other technique is to wrap Java class methods that throw checked exceptions in another util framework class that doesn't throw the exceptions thereby eliminating the unnecessary try/catch statements throughout the code base.

            Just my 2 cents worth...
            Ian
            • SystemAdmin
              SystemAdmin
              757 Posts
              ACCEPTED ANSWER

              Re: Checked vs. Unchecked Exceptions

              ‏2008-03-03T14:27:06Z  in response to SystemAdmin
              The problem is that "some more code" will not get executed and the flow continues
              leading to some mysterious result in some other part of the code
              base that relied on "some more code" getting executed.

              If there was no checking, the developer would not have put in the try/catch with no body.

              ... so just because a developer doesnt understand the flow of execution in a catch block and thus writes code with 'logic errors', means we should get rid of catch blocks so this programmer can hide his ignorance? How does that help? It only pushes the problem to the user of that code. I think I see a good way to eliminate bad programmers in a team from your post! :)
          • SystemAdmin
            SystemAdmin
            757 Posts
            ACCEPTED ANSWER

            Re: Checked vs. Unchecked Exceptions

            ‏2012-11-14T22:10:11Z  in response to SystemAdmin
            Followers of this thread may be interested in an academic paper I have written and am attaching. I propose a solution to the checked exceptions debate. I presented an invited talk on this subject at JavaOne 2012, San Francisco. I am interested in feedback as the article nears publication.

            Duane Buck
  • SystemAdmin
    SystemAdmin
    757 Posts
    ACCEPTED ANSWER

    Re: Checked vs. Unchecked Exceptions

    ‏2004-06-17T14:32:25Z  in response to SystemAdmin
    This article discussed exception handling in a vacuum, not in a real n-tiered application. I would have appreciated examples of checked vs unchecked, nested, etc.. exceptions being used to convey information from one tier to another:
    from a jdbc to an ejb to a soap to a jsf layer...

    On another note, the challenge in error handling, in my experience, has only to be consistent...not perfect. Since many of my developpement teams were often made of junior developpers, most of the problems/bugs were inefficient logs to help solve problems in production. After reading the article, I imagined explaining some of the concepts to these teams and I am sure that many of them would have been more confused than before (not their fault for having little experience).

    just some thoughts...