Discussions

News: Declared Unchecked Exception: The Best of Both Worlds

  1. In "Declared Unchecked Exception: The Best of Both Worlds," an architect suggests deriving exceptions from RuntimeException, and then declaring them in method signatures, providing documentation of exceptions and the ease of use of unchecked exceptions.
    Checked exceptions are used for error conditions that the application can or should handle or that are recoverable. The advantages of checked exceptions are:
    • Making sure the application does not forget to handle the error condition specified by the exception
    • Declared in the throws clause of the method declaration and therefore the error conditions are automatically documented
    But they also carry a few significant disadvantages:
    • In practice, most checked exceptions end up being simply rethrown as unchecked RuntimeException (and lose the type information along the way.)
    • Because of the above, people keep handling the checked exception incorrectly, such as just swallowing the exception (and thereby creating further hard-to-debug errors or even data corruptions) or rethrow it without proper exception chaining. They do so out of ignorance or laziness.
    • Making the method declaration hard to change. If you declare a new checked exception to a method, its calling code will fail to compile because it does not catch that new exception; if you remove a checked exception from the method, its calling code will fail to compile because you catch something that does not occur.
    In addition, while a few exceptions such as NullPointerException, FloatingPointException, and UnsupportedOperationException should inarguably be unchecked exceptions, for the majority of the exceptions, it is highly subjective if they should be checked or unchecked. One can easily start a flame war arguing if IOException should be checked or unchecked. In light of the above issues, many articles such as Does Java Need Checked Exception by Bruce Eckel argue that we should declare only unchecked exceptions like the way Python, C++ and C# are doing. While this design practice solves the limitations of checked exception, common unchecked exception practice introduces other issues. Most APIs that throw only unchecked exceptions either do not declare anything at the throws clause or just declare to throw a high-level unchecked exception... Most other programmers will just write throw new RuntimeException("My error message"); in their code. This apprach would make it very difficult or impossible to accurately handle exceptions.
    The author suggests creating an exception hierarchy based on RuntimeExceptions rather than Exceptions, and then explicitly declaring the exceptions in method signatures. This means that thrown exceptions are unchecked, but very visible. It's a cross between those who say that checked exceptions are not good, and also provides information for those who like declared exceptions. What do you think of this idea? Do you think one day this pattern will be widely acceptable in the Java community? Message was edited by: joeo@enigmastation.com

    Threaded Messages (39)

  2. And what about JavaDoc?[ Go to top ]

    Seems to me that Javadoc does a far more better job of declaring the unchecked exceptions. Why cluther your code with this kind of 'throws' statements? This seems to me like 'separation of documentation'. At some point you need to document what the valid arguments are, for instance: positive integers. You can't document that in the 'throws' clause (okay you can, but it doesn't show up in your IDE).
  3. Try..catch sucks[ Go to top ]

    A) I agree that checked exceptions are a good thing B) I agree that having an unchecked exception bypass is a good thing to have too. C) try catch sucks I think people hate checked exceptions because of the overhead/typing of try...catch. Single-line calls like... File f = File.openmyfile("somefile"); Become try { File f = File.openmyfile("somefile"); } catch (FileNotFound fnf) { logexception(fnf); rollback(); } which is just plain ugly. Now, if you have a bunch of stuff in a row: File f = File.openmyfile("file"); String s = f.readline(); object[] o = s.split("regex"); and every one of those has AT LEAST one required checked exception, you get sick fast of try...catch. So what do most people do? Really Lazy: change method singature to "throws Exception" Lazy: catch (Exception e), generically log, generically rethrow as chained runtime Dutiful: bigger try...catch. File f = null; String s = null; Object[] o = null; try { File f = File.openmyfile(filename); String s = f.readline(); object[] o = s.split("regex"); } catch (FileNotFound) { log("file not found "+filename); } catch (IOException) { log("file status code problem "+f.status);} catch (ParseExceptoin) {log(s+" could not be parsed");} Far more readable than if each of the three statements had their own try..catch, but christ, I need to declare any variables I reference in the catch blocks OUTSIDE of the try catch. How hard is it for java's compiler to maintain lexical scope of the try block for its handling catch blocks so I don't have to waste lines of code declaring local vars outside of the entire try catch block? WTF? Just consider the catch blocks children blocks of the main try statement. Why do we have a variable declaration for the exception? Why do we have to have () around it? why not have a reserved var for that, like say "exception": try { ... } catch FileNotFound { log("msg: "+exception); } catch IOException { log("file empty "+exception.code); } Why not have a special quick syntax for error handling single method calls: File f = File.OpenFile("somefile") %FileNotFound : { do something } %OutOfSpace : log("full"); I'm not even that bright, and I can see obvious improvements.
  4. Re: And what about JavaDoc?[ Go to top ]

    At some point you need to document what the valid arguments are, for instance: positive integers. You can't document that in the 'throws' clause (okay you can, but it doesn't show up in your IDE).
    Documenting exceptions in javadoc is a good practice 8in addition* to declaring it in throws clause. There is no contradition here. In fact, declaring unchecked exceptions in throws clause only helps the IDE to generate the @throws for you in the javadoc. For separation of documentation, yes it is an issue, but it exists for method arguments as well. You have a miserable argument 'i' in the method signature, then you'd better write, separately, "@param i blah blah blah" in javadoc. This can only be solved in Java/javadoc has a way attach documentation diectly to the method param (or the throw declaraiont, for that matter.)
  5. And what about JavaDoc?[ Go to top ]

    Seems to me that Javadoc does a far more better job of declaring the unchecked exceptions. Why cluther your code with this kind of 'throws' statements? This seems to me like 'separation of documentation'. At some point you need to document what the valid arguments are, for instance: positive integers. You can't document that in the 'throws' clause (okay you can, but it doesn't show up in your IDE).
  6. re: And what about JavaDoc?[ Go to top ]

    I wholeheartedly agree that Javadoc (and possibly other tools) should automatically calculate the list of thrown exceptions and automatically include them in the generated documentation. The bit that isn't clear to me is how this would work in the presence of dynamic class loading.
  7. I think it is a good idea. I suggested the same a few months ago in my blog. This is especially useful for IDEs when you do operations like "SURROUND WITH". I've always found checked exceptions rarely useful, but like the idea of easily providing users with the ability to catch appropriate exceptions.
  8. AOP handler advice[ Go to top ]

    ... and not to forget AOP I'm not sure yet, but it should be possible to define a handler advice even for unchecked excpetions mentioned in the throws-clause (not so easy with javadoc ;o))
  9. Visibility is good[ Go to top ]

    Visibility is good, but I think Mark is right. JavaDoc should contain the complete contract of your method, including all thrown exceptions, be it checked or unchecked. Declaring them again violates the DRY principle.
  10. Arg! No move to script language[ Go to top ]

    Of course, IOException and HibernateException are better be unchecked, because 99% of the time, I do the same things with them that I do with OutOfMemoryException, just rollback and abort. I don't have to document them because it may append almost everywhere. But when I have something that is part of my buziness use case, like for an ATM "invalid password" or "no enought money on your account" (things that I have to deal with anyway), I like the compiler to remind me I have to take care of it, anywhere I call the method. I also like the compiler to tell me if an Exception is really throw or not. This is Java: a language where the compiler assist me to document and write my code, at compilation time. I don't like the scripting languages where I don't declare anything and nothing is checked before execution. Adrien
  11. Hi, IMHO checked exceptions also have following good points. 1. Checked exceptions also gives the developer a clue on when to use try-finally block to release resources or clean up dirty stuff when try-finally block is forgotten. They draw the developers attention to possible errors. 2. You are able to just log the error and continue execution of a program if the error is minor since it is very easy to find places where an error can occur. Otherwise you have to think about every possible error-prone code segment and behave accordingly. Regards...
  12. Failing upwards...[ Go to top ]

    This is just horrible. I've worked in C#, and the lack of checked exceptions tops my complaint list. The beauty of checked exceptions is that ones that are likely to occur are easily visible in code. Otherwise, you have to dig in the source or reference the API documentation. Have you ever tried to dig through the Microsoft MSDN reference to see what exceptions something throws? Worse, have you inherited a large application from those before you where absolutely nothing was documented? Just a reminder here, Java was born and developed from lessons learned in languages such as C++. Checked exceptions, managed memory, no pointers, and single inheritance are other difference as well. There is a reason Java is the most widely used language. From the article citing this as a comment from a C# language designer:
    Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result -- decreased productivity and little or no increase in code quality.
    My comment to the above and to those who would ask "Should this be a checked or an unchecked exception" would be the same. It's time for that person to pick up a book and/or dig through the web for how to handle exceptions. I have to seriously question how Microsoft related checked exceptions to decreased productivity in large projects. To me, this sounds like standard corporate BS such as "Well we can't get the checked exceptions integrated, so we should spin a good story". I've been on the other end of the stick, and it isn't pretty. The grass is always greener, until someone runs you over with a lawn mower.
  13. Re: Failing upwards...[ Go to top ]

    Hi Leif, I agree with all your points and I also think checked exceptions are very useful. However, Microsoft's decision not to include checked exceptions in .Net comes from the fact that it needs to support languages that don't have checked exceptions (C and C++). It was not an arbitrary decision... -- Cedric TestNG 5.0 is out!
  14. Thanks[ Go to top ]

    Microsoft's decision not to include checked exceptions in .Net comes from the fact that it needs to support languages that don't have checked exceptions (C and C++).

    It was not an arbitrary decision...

    --
    Cedric
    TestNG 5.0 is out!
    Cool... thanks for the info. I was wondering about that. I figured it was one or the other. Overall I like .NET as well, but the lack of checked exceptions caused me considerably more work. :)
  15. Re: Thanks[ Go to top ]

    Microsoft's decision not to include checked exceptions in .Net comes from the fact that it needs to support languages that don't have checked exceptions (C and C++).

    It was not an arbitrary decision...

    --
    Cedric
    TestNG 5.0 is out!


    Cool... thanks for the info. I was wondering about that. I figured it was one or the other. Overall I like .NET as well, but the lack of checked exceptions caused me considerably more work. :)
    First of all, that's not why checked exceptions were not included. You can read it from the horses mouth so to speak: http://www.artima.com/intv/handcuffs.html Secondly I'm very curious as to how working without checked exceptions caused you more work. I can understand some of the arguments for checked exceptions, but less work has never been one of them. Checked exceptions require more work (which some would argue is a good thing, making you more careful) I personally do not like them for many of the reasons Anders provides and some others. Mostly though they cause developers to unnecessarily handle exceptions that they otherwise should not. In most methods, the correct way of handling an exception is not at all and to let it bubble up to the calling method.
  16. Re: Thanks[ Go to top ]

    In most methods, the correct way of handling an exception is not at all and to let it bubble up to the calling method.
    Exactly. And that's why checked exceptions are not that much more work.

    At any given time, you need to choose whether catching this exception or just put it in your "throws" clause. In my experience, the choice has always been easy most of the time.

    In the end, checked exceptions only force you to write either 0 or 1 catch statement (sometimes a bit more when you wrap and rethrow, but that's a special case), so they don't force you to that much more work.

    The good thing is that they *force* you to think about it.

    While I was not the one who wrote that unchecked exceptions make me do more work, I can agree with this sentiment because unchecked exceptions force you to read a lot of JavaDoc and source code to know exactly what the methods you are invoking can possibly throw. -- Cedric http://testng.org

  17. Re: Thanks[ Go to top ]

    It is possible to argue for and against checked and unchecked exceptions. But I would call the support in Java for checked exceptions for a definate plus. Because if people prefer unchecked they can extend RuntimeException and if they prefer checked they can extend Exception. They have a choice. Except for the Java libaries where SUN has made the decision for us. :-)
  18. Wierd mix of topics[ Go to top ]

    There seem to be two topics running at once here : 1)whether it's a good idea to force developers to handle checked exceptions, and 2) how to document exceptions. These topics are very different and have no useful coupling as far as I can see. Maybe I am missing something ? 1) Checked exceptions are good. In fact, use the compiler to remind yourself to handle exceptions as much as possible. I'm not sure why you'd want to deprive yourself of an automatic safety check. On this topic the suggestion seems absurd. Maybe I misunderstand the suggestion ? I have heard the argument before that developers 'simply leave an empty catch block' for some of these that is, don't really handle them. I guess there are lots of ways of looking at that practice : simply fire people who refuse to follow quality standards, if you care about it that much, or don't worry about it at all; it's just another tool a developer can choose to use or not use, no big deal. 2) Trivial. Do you whatever you want. In my experience, Microsoft is likely correct that worrying about such things will lose productivity in the large scale.
  19. True[ Go to top ]

    simply fire people who refuse to follow quality standards, if you care about it that much, or don't worry about it at all; it's just another tool a developer can choose to use or not use, no big deal.
    That is true. However I will add it makes me wonder what the reasoning is behind not using checked exceptions. Just my own experiences as well, I rarely use runtime exceptions for my own class extensions. Usually I'm extending Exception or Throwable to define custom exceptions. These are then used when the caller violates the method contract.
  20. Re: True[ Go to top ]

    However I will add it makes me wonder what the reasoning is behind not using checked exceptions.
    The reasoning is that a Java program runs the same way as before when you remove all exception specifications (assuming the compiler permitted it). Some "gurus" think that they are therefore useless. I agree with you that checked exceptions are a Good Thing, escpecially in lange projects.
  21. Re: True[ Go to top ]

    What about in a multi-tier project where you want to separate your tiers from one another? Checked exceptions reveal information about downstream tiers. For example, suppose I'm using a relational database as a storage mechanism. If I let SQLException bubble up, then the view layer knows that I'm using JDBC! What if I want to switch to another storage mechanism? Then, I have to refactor all of that code to catch the exception types for that! Of course, I could wrap the exceptions. But then every intermediate tier would have to wrap the exceptions that are downstream from it in order to preserve encapsulation.
  22. Re: True[ Go to top ]

    What about in a multi-tier project where you want to separate your tiers from one another? Checked exceptions reveal information about downstream tiers. For example, suppose I'm using a relational database as a storage mechanism. If I let SQLException bubble up, then the view layer knows that I'm using JDBC! What if I want to switch to another storage mechanism? Then, I have to refactor all of that code to catch the exception types for that! Of course, I could wrap the exceptions. But then every intermediate tier would have to wrap the exceptions that are downstream from it in order to preserve encapsulation.
    Each tier should specify exceptions according to its contract. That means you need to "wrap the exceptions that are downstream from it in order to preserve encapsulation". Would it be better to throw unchecked low level exceptions against your caller?
  23. Re: True[ Go to top ]

    What about in a multi-tier project where you want to separate your tiers from one another? Checked exceptions reveal information about downstream tiers. For example, suppose I'm using a relational database as a storage mechanism. If I let SQLException bubble up, then the view layer knows that I'm using JDBC! What if I want to switch to another storage mechanism? Then, I have to refactor all of that code to catch the exception types for that! Of course, I could wrap the exceptions. But then every intermediate tier would have to wrap the exceptions that are downstream from it in order to preserve encapsulation.
    I don't see any problem with wrapping exceptions to respect the encapsulation level. It's perfectly acceptable to wrap a SQLException into an AccountNotFoundException, and you don't even need to soften the exception when you do this. -- Cedric TestNG
  24. Re: True[ Go to top ]

    I can not see any connection between checked versus unchecked and tiers/layers. Well separated tiers/layers encapsulate all implementation and just exposes an interface. That interface includes exceptions. Checked versus unchecked only means eksplicit versus implicit definition of it. If the code actually throws SuperRevalingAboutImplementationException, then it does not disappear from the interface just by making it unchecked. As states in a previous post then I tend to prefer the explicit.
  25. Let the user decide[ Go to top ]

    Exceptions should be either checked or unchecked, depending on the use case. This allows the user of the exception to decide what's best in the current context. Here's how it works: - For any method which declares that it throws an exception, of any kind, the caller must be prepared to handle it. (declaring an exception makes it checked) - A caller can handle an exception by simply declaring that it too throws it. (nothing new here) - A caller can handle an exception by catching it, doing something, and then discard the exception. (nothing new here) - A caller can simply re-throw the exception, regardless of whether or not it is declared. (this makes it unchecked) Essentially, I can throw whatever exception I like, even without declaring it. In this context, it is unchecked. When I declare that a method throws an exception, I make it checked. The compiler now forces the programmer to do something. The easy thing is to catch and re-throw, but at least some thought had to be given to it. Deciding to always re-throw the exception and thus make it unchecked should be frowned upon, but it is certainly much better than commonly applied practices such as ignore, log-n-drop, or re-throw as RuntimeException. This model provides the best of both worlds, and it lets the programmer decide which makes sense in his/her code. Can it be abused? Of course, but then so can anything.
  26. I think java would only need one exception. Here is what it looks like. class OnceForAllException extends RuntimeExcepion { public String code; public String category; public String message; public String[] parameters; } Since I wrote this exception, I never seem to need write another exception. This exception has a few key benefits: 1. unchecked (runtime) exception: I am a believer in unchecked exception. I totally agree that checked exception does not scale and can't be used inside a framework. 2. I18N support: you can map category to an I18N bundle, parameters are used to hold parameters that are independent of i18n strings. Of course when catching (handling) an exception, instead of using mutiple catch blocks, I have to use if/else/... inside a catch block. But I think this is an advantage because lots of times you want to do something common to some or all the exceptions you are trying to handle (catch). For example, suppose you have to rollback db transaction for some exceptions, instead of doing: ... } catch(FirstExcetion ex) { conn.rollback(); throw ex; } catch(AnotherExcetion ex) { conn.rollback(); throw ex; } catch(ThirdExcetion ex) { conn.rollback(); throw ex; } ... I will do: ... } catch(OnceForAllExcetion ex) { if (ex.getCategory().equals("cat1") && (ex.getCode().equals("code1") || ex.getCode().equals("code2") || ex.getCode().equals("code3") )) { conn.rollback(); } throw ex; } ... Of course, if conn.rollback() is some complex operation, it is very hard to organize your code elegantly using just catch blocks. Someone might say you lose the benefit of type check. But if your exception hierarchy is runtime only, your IDE or compiler won't complain if the exception is missing anyway. Auto-code-completion can be accomplished by defining code and category as string constants. I bet you can't create an exception class for every error condition in your software but you sure should use code for each error condition no matter how weird the error might be. An exception message is never good for exception handling. Codes are much more scalable than exception classes. They are used in operating system calls, DBMS etc. They are more friendly to internationalization too. Now I have a few questions: 1. Do you think one exception is enough? Could you list your reasons no matter you agree or disagree? 2. Do you write an exception class for every error condition? Does it scale? If not, do you use error/exception code? Do you have an alternative solution? Thanks.
  27. I will do:
    ...
    } catch(OnceForAllExcetion ex) {
    if (ex.getCategory().equals("cat1") &&
    (ex.getCode().equals("code1") ||
    ex.getCode().equals("code2") ||
    ex.getCode().equals("code3")
    )) {
    conn.rollback();
    }
    throw ex;
    }
    ...
    What if someone throws "code4"? You have to update all your catch blocks. BTW, you roll back a db transaction in finally, not in a catch block!
  28. No, you don't rollback your transaction in finally. Normally you would commit your transaction. Rollback should only take place upon exception. But for certain cases of exception I don't want to rollback my transaction. In addition, the conn.rollback() code is only for illustration purpose.
  29. I think java would only need one exception. Here is what it looks like.
    class OnceForAllException extends RuntimeExcepion {
    public String code;
    public String category;
    public String message;
    public String[] parameters;
    }
    Wow... What a horrible idea... Where to start? First of all, you are already limiting your options by only using unchecked exceptions, but with this approach, you are creating amounts of spaghetti code that I'm betting your coworkers are not very amused with. Second, you are replacing the very flexible language-level catch construct with an if-else. Add a "code" (a String? Seriously?) to your system and suddenly, you have to manually find all your if-else in your entire system and figure out which ones need to be updated and which ones don't. And for those that don't, what do you do? Rethrow? So now you have a mix of catch that sometimes do something and sometimes rethrow. Third, when I call one of your method, it throws this exception (I'm betting 90% of your methods throw that exception by now) and I have *no idea* which codes can be thrown. What should I refer to? JavaDoc? Tea leaves? My advice: drop your system altogether, put checked exceptions back into your toolbox, create a sensible exception hierarchy and when a method needs to throw, pick the most appropriate choice among these three. -- Cedric TestNG
  30. Wow... What a horrible idea...
    I know someone would say this :)
    First of all, you are already limiting your options by only using unchecked exceptions,
    Like many others, I think checked exception has lots of problems, so there is only unchecked exception left.
    but with this approach, you are creating amounts of spaghetti code that I'm betting your coworkers are not very amused with.
    Why do you claim it is spaghetti code? I used the exception in our code and our code is much cleaner. Of course the benefit is mainly from unchecked exception (no more useless try-catch blocks).
    Second, you are replacing the very flexible language-level catch construct with an if-else. Add a "code" (a String? Seriously?) to your system and suddenly, you have to manually find all your if-else in your entire system and figure out which ones need to be updated and which ones don't.

    And for those that don't, what do you do? Rethrow? So now you have a mix of catch that sometimes do something and sometimes rethrow.
    Use string CONSTANTS, instead of just strings. Adding an exception is the same as adding a code, you still have to go through all the code. The OnceForAllException has a hierarchy built in: category + code. It is I18N friendly. It also gives you fine error conditions which you can choose to act on.
    Third, when I call one of your method, it throws this exception (I'm betting 90% of your methods throw that exception by now) and I have *no idea* which codes can be thrown. What should I refer to? JavaDoc? Tea leaves?
    Obviously javadoc would be one place. Clearly there could be others like category/code registry etc (any advice would be welcome).
    My advice: drop your system altogether, put checked exceptions back into your toolbox, create a sensible exception hierarchy and when a method needs to throw, pick the most appropriate choice among these three.

    --
    Cedric
    Thanks for the advice. Unfortunately checked exception is no longer an option. Please think again.
  31. Let us see: - public fields - testing on data instead of building behaviour into types That seems like a catastrophic lack of understanding of object oriented principles ! (no matter whether one like checked exceptions or not)
  32. Let us see:
    - public fields
    - testing on data instead of building behaviour into types

    That seems like a catastrophic lack of understanding
    of object oriented principles !

    (no matter whether one like checked exceptions or not)
    What's the behavior in an exception? try catch catch catch catch is ugly. It's far worse than using if.
  33. Let us see:
    - public fields
    - testing on data instead of building behaviour into types

    That seems like a catastrophic lack of understanding
    of object oriented principles !

    (no matter whether one like checked exceptions or not)
    the code is for illustration purpuse, in the real implementation the fields are private with getter/setters.
  34. I think java would only need one exception. Here is what it looks like.
    class OnceForAllException extends RuntimeExcepion {
    public String code;
    public String category;
    public String message;
    public String[] parameters;
    }

    What about exception inheritance? When doing io, do you really want to handle FileNotFoundException, FileLockInterruptionException, MalformattedURLException etc instead of just catching IOException? OK, you *could* implement an inheritance mechanism in your category code system, but I guess you'll agree that would be a major wheel reinvention, when you already have a working inheritance mechanism in the language.
  35. What about exception inheritance?

    When doing io, do you really want to handle FileNotFoundException, FileLockInterruptionException, MalformattedURLException etc instead of just catching IOException?

    OK, you *could* implement an inheritance mechanism in your category code system, but I guess you'll agree that would be a major wheel reinvention, when you already have a working inheritance mechanism in the language.
    The problems I am trying to solve are: 1. checked exception does not work well (so the unchecked exception is extended) 2. we can't create an exception for each error condition 3. just message in an exeption is not sufficient, we need code to decide if the exception can be handled. Of course theoretically we can create a new exception for each error code but I don't think it is feasible. I started trying to build a base exception with "code", "message", "parameters" but when that exception is completed with addition of "category" I found there is no need for any additional exception. That's why I am sharing my experience and seeking advice from the community.
  36. The problems I am trying to solve are:
    1. checked exception does not work well (so the unchecked exception is extended)
    2. we can't create an exception for each error condition
    3. just message in an exeption is not sufficient, we need code to decide if the exception can be handled. Of course theoretically we can create a new exception for each error code but I don't think it is feasible.

    I started trying to build a base exception with "code", "message", "parameters" but when that exception is completed with addition of "category" I found there is no need for any additional exception. That's why I am sharing my experience and seeking advice from the community.
    I think that you will find that the best approach is to mix normal exception inheritance with error codes. I.e. it is wise to have a specific exception type for each specific error condition that code must react to, and to use error codes to distinguish between error conditions which are handled the same way in code but which need to be logged differently etc. Take IOException as an example - there might be a lot of code that wants to handle End of file differently than File not Found - hence the two subclasses EOFException and FileNotFoundException. Then think about a MOM implementation - lets say that you cant connect to an MQQueueManager (as in IBM WebSphere MQ). Now, all your code needs to know is that it cant connect - but for logging and error correction you need to know the exact cause of the problem - and so you have some one thousand and one error codes wrapped in the exception. Also, I cant agree with the assertion that checked exceptions doesnt work. For a small program they might cause some extra work, but for a larger project with many developers they are a great way to document the error conditions that can occur in a method, and force callers to deal with them, as well as making refactoring and extension of the code a lot easier.
  37. I.e. it is wise to have a specific exception type for each specific error condition that code must react to, and to use error codes to distinguish between error conditions which are handled the same way in code but which need to be logged differently etc.
    I guess that what I am trying to say here is that if you need to branch based on the error code, then it shouldnt have been an error code, but a new exception type instead.
  38. Exceptions + log[ Go to top ]

    The checked exceptions along with cahining provide a useful mechanism to accumulate the state of the application and log it once. Imagine that we have a class A, which holds some valuable application state. This class calls class B, which throws an exception. If we used runtime exception - the information from class A is lost by the time we log. With checked exception you can simply catch it in the class A and chain into a new (probably more generic) exception along with the state information from the class A. The logging rule is simple - log it only when you stop chaining (e.g. leaving tier or container). Unfortunately, you can't keep log level = debug on a production system and problem investigation becomes a nightmare with runtime exceptions. Also, incorrect (e.g. empty catch sections) implementation can be easily found by checkstyle or anything similar. So, my conclusion always was to use "checked exception + chaining + logging once" for production code, although runtime exceptions can be good for frameworks.
  39. Trouble with Checked[ Go to top ]

    My trouble with Checked Exception is that its not an interface. When you refactor a class to generalize it into multiple interfaces - the method parameters and return types can easily be generalized along-side - but not its declared Exceptions. Nesting them will only work sometimes (besides being an incredibly tedious task). Essentially your Exception heirarchy will never be able grow parallel with the class/interface heirarchies that declare them. As a side note: Maybe use a standard Annotation such as: @throws(XyzException.class) and have a RuntimeException heirarchy ??? that way atleast it is docuemnted well and part of the method but still flexible.
  40. Whether you have some coding guidelines that require people to add notes about exceptions in the JavaDoc comments about unchecked exceptions or you have some coding guidelines that require people to add a throws clause for unchecked exceptions is no big difference. I can really not see the point in this suggestion. Both a conventions not something enforced. And it is 100% sure that occasionally someone will forget to put it there. If the design is to use unchecked exceptions, then developers should be prepared for unexpected unchecked exceptions. I tend to prefer checked exceptions, but I am not religious about it.