Exception chaining in JDBC

Discussions

News: Exception chaining in JDBC

  1. Exception chaining in JDBC (51 messages)

    Jonathan Bruce, JDBC 4.0 spec lead, has written up his thoughts on allowing SQLException to take a Throwable, allowing easy exception chaining. He also discusses the fact that the 4.0 expert group is "looking to provide a limited set of exceptions that relate directly to SQL State definitions".

    Excerpt
    By defining a group of methods that allow a Throwable instance to be set at the SQLException level, this allow related exceptions definition introduced in JDBC RowSets to also provide chaining support. Overloading the current set of constructors should achieve chaining functionality and compliment the four other currently defined constructors.

    public SQLException(Throwable cause);

    public SQLException(String reason, Throwable cause);

    public SQLException(String reason, String sqlState, Throwable cause);

    Intertwining this with a an additional proposal underway in JDBC 4.0 which is looking to provide a limited set of exceptions that relate directly to SQL State definitions should provide an improved standard API so developers can more easily port the applications between different SQL data sources.
    What would you like to see? Subclasses a la Spring?

    Read Exception chaining in JDBC

    Threaded Messages (51)

  2. Long overdue...[ Go to top ]

    ... those will be useful enhancements. Anyways, I've seen a lot of code that is constrained by an interface or whatever to throw SQLException do things like
    try {
     ...
    } catch (Exception e) {
      SQLException sqle = new SQLException("some message");
      sqle.initCause(e);
      throw sqle;
    }

    So SQLException chaining will allow above code to be cleaned up ;)
  3. Closures make the code clean :)[ Go to top ]

    Whenever I see a lot of JDBC code, I am thankful for closures (or using Template patterns).

    I enjoy doing simple SQL tasks in Groovy:
    sql = new Sql(DBUtil.getConnection())

    sql.eachRow("select * from users where userpk=$null") {
     name = "${it.firstname} ${it.lastname}"
     ...
    }
    and in Spring:
    JdbcTemplate template = new JdbcTemplate(dataSource);
    final List names = new LinkedList();
    template.query("SELECT USER.NAME FROM USER",
    new RowCallbackHandler() {
    public void processRow(ResultSet rs) throws SQLException {
    names.add(rs.getString(1));
    }
    });
    Dion
  4. @SQL "SELECT USER.NAME FROM USER"
    abstarct List<String> findAllNames();
  5. Subclasses![ Go to top ]

    A sprinkling of subclasses, such as for unique or foreign key constraint violation.
  6. Like Spring?[ Go to top ]

    Isn't exactly what Spring provide?
  7. Like Spring?[ Go to top ]

    Except that Spring's exceptions are not checked exceptions. No need to catch them unless you think you can handle them. Spring attempts to translate any SQLExceptions based on the database specific Error Code and it will fallback to using the SQL State if the Error Code can not be translated. This is all customizable in an XML file. Spring currently provides translation to the following categories (all extending RuntimeException):

    BadSqlGrammarException,
    DataIntegrityViolationException,
    DataRetrievalFailureException,
    OptimisticLockingFailureException,
    DataAccessResourceFailureException and
    UncategorizedSQLException

    We are planning on expanding this in a future release and even allow translation to user provided exceptions.

    If JDBC 4.0 would specify some sub-classes for SQLException that did indicate the type of error, then that would make Spring's translation a lot easier. The SQL State is not used in a very consistent manner across all the database vendors.

    Thomas
  8. Like Spring?[ Go to top ]

    Except that Spring's exceptions are not checked exceptions. No need to catch them unless you think you can handle them.
    The way Spring forces developers to rely on runtime semantic in dealing with JDBC related code is probably most dangerous hole in Spring design (among many others not so serious). It’s understandable that Rod Johnson was blinded by Servlet JSR participation and that’s where I guess this “idea” came from, but to this day assume that all development should conform to JSP container is just silly at best.

    Regards,
    Nikita Ivanov.
  9. Like Spring?[ Go to top ]

    Why do you think it is more dangerous than SQLException ?
  10. Checked Vs Runtime
  11. Checked Vs Runtime
    Yes, it was dicussed many times, nobody can prove "Checked" exeption can be usefull in any context and in practice checked exeption produce more problems than solve (it is very clear from this article too). Runtime exeptions solve no problems, but do not cause any problems too.
  12. Like Spring?[ Go to top ]

    The way Spring forces developers to rely on runtime semantic in dealing with JDBC related code is probably most dangerous hole in Spring design (among many others not so serious). It&#8217;s understandable that Rod Johnson was blinded by Servlet JSR participation and that&#8217;s where I guess this &#8220;idea&#8221; came from, but to this day assume that all development should conform to JSP container is just silly at best. Regards,Nikita Ivanov.
    Your assumption that the runtime exception choice has anything do with a JSP container (??) is odd. The only criterion here is whether the caller of a DAO typically has any chance to handle data access exceptions: We assume it hasn't, so does JDO (note: on its resource API like PersistenceManagerFactory and PersistenceManager, not just on manipulated persistent objects). Even Gavin King from Hibernate stated that he regrets having chosen checked exceptions.

    I'm not keen on having yet another checked/unchecked exception debate, Nikita. Most importantly, please stop spreading FUD a la "most dangerous hole in Spring" - it simply isn't true. Spring's DAO support classes are coded such that there will always be proper resource and transaction cleanup. We have not had a single complaint about data access exceptions being unchecked from an actual user yet, despite widespread usage of our DAO support.

    Checked SQLException may be OK for the low-level JDBC API, but IMO, once you pass facades like DAOs (that care for proper cleanup internally), there's not much point in rethrowing checked data access exceptions. The callers of DAOs, i.e. typically business services, cannot deal with data access exceptions in most cases. And if they can for specific (unchecked) exceptions like OptimisticLockingFailureException, they can still catch those.

    Please accept that there are multiple views on this subject, and that a design that does not follow your own view is not automatically a "dangerous hole". What's usually really devastating is ad-hoc catching of SQLExceptions and unreflected swallowing or rethrowing via "throw new RuntimeException(sqlex)"; that's still seen too often. One of the purposes of Spring's DAO support is to replace such crude solutions with a safe and sophisticated approach.

    Juergen
    http://www.springframework.org
  13. Like Spring?[ Go to top ]

    Hi Juergen,
    Let me address some of this:
    Your assumption that the runtime exception choice has anything do with a JSP container (??) is odd.
    I meant that initial design most likely came from working with JSP only. In JSP context runtime exception do make sense, yet as more-then-JSP framework usage of runtime exception (forced usage) is a clear mistake in my view.
    The only criterion here is whether the caller of a DAO typically has any chance to handle data access exceptions: We assume it hasn't, so does JDO (note: on its resource API like PersistenceManagerFactory and PersistenceManager, not just on manipulated persistent objects). Even Gavin King from Hibernate stated that he regrets having chosen checked exceptions.
    You just pointed another major problem with JDO... As far as Gavin King, well, there are 1000s of engineers still beliving they can build complex systems in Perl...
    I'm not keen on having yet another checked/unchecked exception debate, Nikita. Most importantly, please stop spreading FUD a la "most dangerous hole in Spring" - it simply isn't true.
    It's my personal opinion and I've stated it clear. Spring has gaping hole in JDBC/DAO design that makes it unsuitable for any but simplistic development outside of JSP container. Simple and clear. I hope you get it this time.
    Checked SQLException may be OK for the low-level JDBC API, but IMO, once you pass facades like DAOs (that care for proper cleanup internally), there's not much point in rethrowing checked data access exceptions. The callers of DAOs, i.e. typically business services, cannot deal with data access exceptions in most cases. And if they can for specific (unchecked) exceptions like OptimisticLockingFailureException, they can still catch those.Please accept that there are multiple views on this subject, and that a design that does not follow your own view is not automatically a "dangerous hole". What's usually really devastating is ad-hoc catching of SQLExceptions and unreflected swallowing or rethrowing via "throw new RuntimeException(sqlex)"; that's still seen too often. One of the purposes of Spring's DAO support is to replace such crude solutions with a safe and sophisticated approach.
    Well, that's your personal opinion and you can obviosly can have it. You and I disgree on that.

    Best regards,
    Nikita Ivanov.
  14. Like Spring?[ Go to top ]

    I meant that initial design most likely came from working with JSP only. In JSP context runtime exception do make sense, yet as more-then-JSP framework usage of runtime exception (forced usage) is a clear mistake in my view.
    Could you please bother to explain why that is supposed to be related to JSP? Whole general programming environments rely on unchecked exceptions only, so this is a debate that doesn't have to do *anything* with JSP.
    You just pointed another major problem with JDO... As far as Gavin King, well, there are 1000s of engineers still beliving they can build complex systems in Perl...
    And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    It's my personal opinion and I've stated it clear. Spring has gaping hole in JDBC/DAO design that makes it unsuitable for any but simplistic development outside of JSP container. Simple and clear. I hope you get it this time.
    Where did you actually state that this was your personal opinion? I can't find a single "IMO" or the like in your original post - just harsh, unbalanced words and the label "silly". And thanks for hoping that I "get it this time".

    You probably wouldn't believe in what kinds of environments Spring's JDBC support is used already (hint: finance, mission-critical next-gen systems). Many Spring usages happen completely outside a web environment.
    Well, that's your personal opinion and you can obviosly can have it. You and I disgree on that. Best regards,Nikita Ivanov.
    We obviously disagree. However, there is a difference between disagreeing on a general issue and spreading FUD about a specific product. Particularly if you work for a company that builds a competing application framework.

    Juergen
  15. I can't find a single "IMO" or the like in your original post - just harsh, unbalanced words and the label "silly".
    This is a forum where _people_ send posts therefore all posts to be prefixed by IMO, unless text states otherwise with BS phrases like: as it well known…, everybody knows etc…

    And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    At least 3: Nikita, Me and Gosling.
  16. This is a forum where _people_ send posts therefore all posts to be prefixed by IMO, unless text states otherwise with BS phrases like: as it well known…, everybody knows etc…
    Sure - but Nikita insists that he "clearly stated" that this was his personal opinion rather than a generally accepted fact. In that case, I expect to find at least some IMO-like phrase.
    And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    At least 3: Nikita, Me and Gosling.
    That comment of mine was obviously sarcastic. I am well aware that there are multiple viable views. It's clear that "dangerous hole" anti-propaganda doesn't help, though. Did you see any concrete issues outlined in Nikita's post?

    I am by no means against checked exceptions, just against their overuse for system-level stuff. I believe that *application exceptions* should be checked in most cases. It's about a balance in the middle, not about black and white.

    What was this thread originally about again? Can we *please* leave the FUD behind and return to JDBC 4.0?

    Juergen
  17. Juergen:
    And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    Konstantin:
    At least 3: Nikita, Me and Gosling.
    At least 4: Add me to the list too :-)
  18. Juergen:And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    Konstantin:At least 3: Nikita, Me and Gosling.
    At least 4: Add me to the list too :-)
    OK, before this becomes a black and white popularity contest, an even clearer disclaimer: That comment was sarcastic, in reaction to Nikita's 1000-engineer comment. It was specifically referring to systems that are built on checked exceptions only, for any kind of exception.

    To understand what this is about, please check out earlier threads, in particular where both Nikita and I participated. And note that Nikita works for a company that sells a suite of Java/.NET middle tier components; this might account for the lack of concrete issues and the amount of FUD against Spring.

    As I already indicated (and said repeatedly on TSS before), I agree that checked exceptions are important for application exceptions - but not for system exceptions that typically cannot be dealt with in a specific fashion in higher application layers. IMHO, and I do not call other views "silly".

    Has anyone already figured out how this is supposed to relate to JSP containers? ;-)

    Juergen
  19. Speaking of...[ Go to top ]

    Juergen,
    It was specifically referring to systems that are built on checked exceptions only, for any kind of exception.
    I thought you were smarter than that. I never said only, as the matter of fact I said that in JSP scenario it's accepted practice due to the way Servlets were originally designed. But again, as another poster has said it's been discussed to death already. And frankly, I'm not posting here to convert anyone but just to dispel some of the myths... As a community we've been through this with JBoss and it was helpful for sure.
    And note that Nikita works for a company that sells a suite of Java/.NET middle tier components.
    Very correct observation. We, however, don't compete with Spring (or any other open source projects for that matter). Indeed, Spring functionality is a very small percentage of what we do. I don’t want to plug about what we do in details, but here’s some flavor:
    * fully componentized middleware for Java and/or .NET, buy/use component by component avoiding framework lock-in and “rip & replace” integration
    * first cross-paradigm Java and .NET middleware
    * 2-way micro-kernel based integration with practically any Java or .NET environment such as J2EE servers, Web containers, proprietary middleware, .NET environment, Yukon sever, etc.
    * 20+ services for Java and .NET:
       - distributed cluster management
       - non-replicable distributed cache
       - grid computing
       - hierarchical configuration
       - system workflow engine
       - etc, etc, etc…
    * all services are fully IoC/DI based
    * automatic JMX/MMC instrumentation
    * "out-of-box" integration with 7 leading J2EE app servers
    * IDE plugins for 6 leading Java IDEs
    * etc, etc, etc…

    I could go on but it’s clear we’re in different space (look at the website or download it if you are not convinced yet).

    And by the way, we do use some runtime exceptions where it’s appropriate. However, most of them are checked and for a good reason. So, trying to say that my comments are motivated by competition will not fly as these tactics never work and are easily disproved, Juergen.

    Despite my criticism, I wish the best of luck to Spring team, in the end, it's clear that people are putting effort into it.

    Best regards,
    Nikita.
  20. Speaking of...[ Go to top ]

    Nikita,
    Very correct observation. We, however, don't compete with Spring (or any other open source projects for that matter). Indeed, Spring functionality is a very small percentage of what we do. I don’t want to plug about what we do in details, but here’s some flavor: ...
    Well, that was quite a plug, but never mind. Am I supposed to start saying that your product strategy is "silly" and "not able to work with JSP containers" now? ;-)
    So, trying to say that my comments are motivated by competition will not fly as these tactics never work and are easily disproved, Juergen.
    I'm not saying that your comments are purely motivated by competition. But you're definitely biased and can't really deny a certain vested interest in dismissing open source application frameworks for mission-critical applications. I still honor your right for a public opinion, of course.
    Despite my criticism, I wish the best of luck to Spring team, in the end, it's clear that people are putting effort into it.Best regards,Nikita.
    I really appreciate that fairness - the best of luck for your efforts too. I do understand that you really believe in what you're advocating. However, I just expect a bit more respect for other views and products... Now, let's end this discussion and let the thread turn back to JDBC 4!

    Juergen
  21. Speaking of...[ Go to top ]

    Hi Juergen,
    I know it's not about JDBC4 but I believe that that topic was quite clear anyways... :-)
    Well, that was quite a plug, but never mind. Am I supposed to start saying that your product strategy is "silly" and "not able to work with JSP containers" now? ;-)
    Now, that's an interesting direction. We specifically avoid Model2 and ORM functionality in both Java and .NET editions of our product as I believe this place is already over-saturated with commercial and open source products and it is hard to bring any additional value to the customers.
    But you're definitely biased and can't really deny a certain vested interest in dismissing open source application frameworks for mission-critical applications.
    I, of course, believe that xTier™ is the best product in its category. No surprises here. And I always try to dispel certain myths about other products (OS or commercial) that can have any relevance to what we do.

    Best regards,
    Nikita.
  22. Juergen:And there is at least 1 engineer that obviously believes that complex systems can only be built on checked exceptions.
    Konstantin:At least 3: Nikita, Me and Gosling.
    At least 4: Add me to the list too :-)
    +1

    But hasn't been this argued to the death yet? Like here.
  23. Criticism is not FUD[ Go to top ]

    Juergen:
    We obviously disagree. However, there is a difference between disagreeing on a general issue and spreading FUD about a specific product.
    Juergen,
    It is immature to qualify all opinions that criticize Spring as FUD. If this forum was only about positive feedback then nobody would read it. Maybe it’s time that Spring team grew a thicker skin.

    My stand on checked/unchecked exceptions is well known and I side with Nikita that due to unchecked-exceptions-nature of Spring, use of Spring API’s (DAO in this example) will lead to many hidden un-handled errors in production systems and therefore should never be used in any complex and especially _mission-critical_ applications.

    Neither Nikita nor anyone else in this thread believes that systems can be exclusively built on checked or unchecked exceptions. Correct balance should always be maintained and by no means should robustness ever be sacrificed.

    And please don’t label this post as FUD...

    Dmitriy.
  24. Criticism is not FUD[ Go to top ]

    It is immature to qualify all opinions that criticize Spring as FUD. If this forum was only about positive feedback then nobody would read it. Maybe it’s time that Spring team grew a thicker skin.
    The line between feedback and FUD is thin. Nikita's initial post qualifies as FUD by any means: The choice of words there is far from constructive feedback and quite insulting. Talking about a competing product in such a way is the really immature behavior, IMHO.
    My stand on checked/unchecked exceptions is well known and I side with Nikita that due to unchecked-exceptions-nature of Spring, use of Spring API’s (DAO in this example) will lead to many hidden un-handled errors in production systems and therefore should never be used in any complex and especially _mission-critical_ applications.
    While you're of course entitled to that opinion, your criticism is very simplistic. Overuse of checked exceptions can lead to a lot of maintainability issues in complex systems too, particularly if developers start to handle them in inappropriate ways. This is not a simple black and white choice.

    Finally, you might disclose that you work for Fitech Labs too, just like Nikita, selling commercial middle tier components. Both of you are not unbiased in the first place, and obviously have an interest in publically dismissing Spring's suitability for mission-critical applications.

    Juergen
  25. Criticism is not FUD[ Go to top ]

    While you're of course entitled to that opinion, your criticism is very simplistic. Overuse of checked exceptions can lead to a lot of maintainability issues in complex systems too, particularly if developers start to handle them in inappropriate ways. This is not a simple black and white choice.
    Here we go again... Just because not all the people use checked exceptions correctly, Spring framework comes in and dismisses the whole concept altogether. You say “maintainability”, “mishandling” – and I say it’s bogus. Applications well designed will never have any of those issues with checked exceptions.

    Instead of theorizing about runtime vs. checked, when developing our product (href="xTier™)in" rel="nofollow">xTier™" rel="nofollow">http://www.fitechlabs.com/products_xtier_overview.jsp">xTier™)in Java and .NET we have gained a great deal of experience in error handling within environments that do and don’t support checked exceptions. We can attest first hand that checked exceptions are absolutely vital especially when designing API’s and system level code. We even developed an AOP-based tool to introduce checked exceptions into .NET CLR.

    I do believe that our experience more than qualifies us to make a judgment on this matter.
    Finally, you might disclose that you work for Fitech Labs too, just like Nikita, selling commercial middle tier components.


    Well...
    If anyone does not know it yet, I do work for Fitech Labs. Just look into history of my posts and it will become more than obvious. To imply that I was hiding it – you must be working for Open Source project ;-)

    Dmitriy.
  26. Criticism is not FUD[ Go to top ]

    It is immature to qualify all opinions that criticize Spring as FUD. If this forum was only about positive feedback then nobody would read it. Maybe it’s time that Spring team grew a thicker skin.
    The line between feedback and FUD is thin. Nikita's initial post qualifies as FUD by any means: The choice of words there is far from constructive feedback and quite insulting. Talking about a competing product in such a way is the really immature behavior, IMHO.
    Wait, can you hear it - it the scramble for the righteous high ground, quick get out of the way for fear of being trampled – this wailing and wounded indignation gets old really fast.

    If someone has a fundamental disagreement with the way in which you've implemented something, or they have an opinion about something then that's their right. Furthermore “IMO” or “IMHO” is really irrelevant to a posting signed by someone, I mean defacto, its their opinion, unless it’s someone else's ... oh wait, wrong thread ;)

    The thing that I don’t think you seem to understand and, (IMO) is the most insulting part of this is the way in which you have infantilized the TSS readership. People read these discussions with a critical eye, if they are interested in a given technology, then they will evaluate it. I do not know anyone, customer, developer, prospect, competitor that takes what is written in these forums verbatim.

    By wailing about “FUD” you have reduced the reader of this forum to a mindless automaton. If you product won’t stand on its own when held up to a critical analysis (something which I think, and I am sure that you will agree, that Spring can indeed do), then what is the problem?
    My stand on checked/unchecked exceptions is well known and I side with Nikita that due to unchecked-exceptions-nature of Spring, use of Spring API’s (DAO in this example) will lead to many hidden un-handled errors in production systems and therefore should never be used in any complex and especially _mission-critical_ applications.
    While you're of course entitled to that opinion, your criticism is very simplistic. Overuse of checked exceptions can lead to a lot of maintainability issues in complex systems too, particularly if developers start to handle them in inappropriate ways. This is not a simple black and white choice.Finally, you might disclose that you work for Fitech Labs too, just like Nikita, selling commercial middle tier components. Both of you are not unbiased in the first place, and obviously have an interest in publically dismissing Spring's suitability for mission-critical applications.Juergen
    If the comments aren't "true" or "correct" or are “simplistic” then do you really think that the "uninformed readers" are going to swallow it? As for “interests” you clearly have a vested interest in squashing anyone who has an opinion about your product that is less than glowing. I encourage and applaud you for defending your product, but please, grow a thicker skin and ease up a bit.

    And to finish, just so we’re clear:

    All of the opinions expressed in this post are mine, mine only, no one else’s, IMO, IMHO all applied liberally. And yes, I work at Fitech Labs, with Dmitriy, and Nikita, and we do indeed have a product called xTier that doesn’t compete with Spring. Caveat Emptor - No warranties implied or stated about this post. One does not have to read nor respond to my post unless one feels compelled to. In fact, you don’t have to do anything at all.

    Respectfully,
    Jon
  27. Criticism is not FUD[ Go to top ]

    You guys at xTier seem to be the most touchy here: Nikita's post was clearly offensive, anyone can see that. (BTW: I don't work for, use, or have any relation to any party or product involved in the discussion.)
    From the provided xTier description, anyone can see clearly that both products compete in more than one aspect, so Juegen is right to say that you guys are biased. Worse: it takes three of you to fight him alone in this discussion, it that really needed? If this was a simple thing, it wouldn't take more than one person's argument. Now it seems the whole company is out there to fight against "the myths", as if what Juegen says was a blasphemy. He has already shown that he has a different view of things, so calling it "myth" can be regarded as FUD too.

    So you guys, calm down, and fight with you product, and not with your word, as you have so rightfully preached. This discussion will take us nowhere, it has already been extended beyound reason and logic, there are simply different views and opinions on it, so accept it and get along.

    Regards,
    Henrique Steckelberg
  28. "The way xTier forces developers to rely on compiletime semantic in dealing with JDBC related code is probably most dangerous hole in xTier design (among many others not so serious). It’s understandable that Nikita was blinded by Fitech Labs participation and that’s where I guess this “idea” came from, but to this day assume that all development should conform to Fitech's container is just silly at best."

    Now tell me if the above "loose" comparation can be called offensive and FUD to xTier or not, as the original post was to Spring...
  29. Criticism is not FUD[ Go to top ]

    "The way xTier forces developers to rely on compiletime semantic in dealing with JDBC related code is probably most dangerous hole in xTier design (among many others not so serious). It’s understandable that Nikita was blinded by Fitech Labs participation and that’s where I guess this "idea" came from, but to this day assume that all development should conform to Fitech's container is just silly at best."Now tell me if the above "loose" comparation can be called offensive and FUD to xTier or not, as the original post was to Spring...
    Henrique,
    This is a neat way to put it. All fun aside however, I would challenge you to find the real problem(s) in our product to make this statement correct. You can download it from http://www.fitechlabs.com/products_xtier_download.jsp.

    Good luck,
    Nikita Ivanov.
  30. Criticism is not FUD[ Go to top ]

    "The way xTier forces developers to rely on compiletime semantic in dealing with JDBC related code is probably most dangerous hole in xTier design (among many others not so serious). It’s understandable that Nikita was blinded by Fitech Labs participation and that’s where I guess this "idea" came from, but to this day assume that all development should conform to Fitech's container is just silly at best."Now tell me if the above "loose" comparation can be called offensive and FUD to xTier or not, as the original post was to Spring...
    Henrique,This is a neat way to put it. All fun aside however, I would challenge you to find the real problem(s) in our product to make this statement correct. You can download it from http://www.fitechlabs.com/products_xtier_download.jsp.Good luck,Nikita Ivanov.
    You haven't adressed my question here: can my "version" of what you said be considered FUD or offensive or not? This has nothing to do with your product being good or not, as I am not doubting it is, I am referring to your particular style of putting down "facts" that are "clear".
  31. Criticism is not FUD[ Go to top ]

    Hi Henrique,
    I will try to respond as long as I have time for it so apologize in advance if drop out and leave something unanswered.
    You guys at xTier seem to be the most touchy here: Nikita's post was clearly offensive, anyone can see that.
    I'm really getting tired of a constant whining about “wounded innocence” of certain projects. I don’t see anything offensive in my comments at all but rather simple facts that I stated (hopefully very clear). Those facts, in my opinion, are very hard to argue with. I do strongly believe that a middleware software with broken error handling, or broken threading model, or broken usage patterns, etc. do more harm than good to the end user. These things are not just mere inconvenience or missing features – they are fatal problems for middleware.


    Off topic (twice :-) : this whole issue reminds me the eternal “battle” between Mike Spille and JBoss. Not to steal any fame but there are just too many similarities…


    As I have stated many times, the error handling in JDBC part of Spring falls into this category. Many people from Spring have publicly said that this is indeed a “great feature” of Spring and so I am trying to argue with that.

    As I said somewhere above, so-called “competition” has nothing to do with it. There is more competition between Cameron’s Tangosol product and our Distribute Cache service – one of our 20+ services. I know it sounds cheese, but we are in a different league, so to speak, comparing to Spring.

    Now, coming back to error handling, we at Fitech have an unique expertise in this area as the only few people who develop complex system middleware on both Java and .NET platforms (no native checked exception support) for almost 3 years and have deep understanding of error handling on large and very large systems. As it was mentioned above, instead of pure theorizing, we deal with this issue on a daily basis in the system that is statistically big enough to draw certain definitive conclusions.

    The irony of this discussion though is that we at Fitech are actually glad that Spring and other lightweight frameworks do exist. We don’t compete but they help to popularize many ideas and principles that we believe in too and that ultimately helps us to sell our software.

    Best of luck,
    Nikita Ivanov.
  32. Criticism is not FUD[ Go to top ]

    Off topic (twice :-) : this whole issue reminds me the eternal “battle” between Mike Spille and JBoss. Not to steal any fame but there are just too many similarities…
    That comparison is far-fetched and more or less invalid. Mike Spille is not involved with a J2EE server vendor but is a pure user in relation to JBoss and other J2EE servers. You and your colleagues on the other hand do sell a product that at least remotely competes with Spring, so this is a completely different matter. I think this is clear for any TSS reader; don't infantilize them ;-)

    Furthermore, Mike Spille always pointed out concrete scenarios and concrete issues, down to the implementation level; that's what many people appreciated. What you're doing is FUDing a general design design of Spring, without giving any concrete scenario where it causes a real problem - just because you took a different design decision that you consider the heart of your own product.

    At least, thanks for the implicit recognition: If you considered Spring irrelevant for your company, you wouldn't bother to do such much anti-propaganda in a public forum. Continue to claim that you don't compete with Spring - your actions indicate something entirely different. (For everybody interested, note that Nikita and Jon are members of Fitech's management board!)

    As I've been personally offended numerous times in this thread - which does seem to reach new climaxes rather than calm down -, I'm outta here. I don't see the point in continuing a PR fight with 3 (!!) representatives of a commercial framework vendor that don't show respect for design alternatives in competing products and continue to more or less subtly offend the people behind them.

    Juergen
  33. Criticism is not FUD[ Go to top ]

    "use of Spring API&#8217;s (DAO in this example) will lead to many hidden un-handled errors in production systems and therefore should never be used in any complex and especially _mission-critical_ applications."

    Collection findAll()
               throws BugInSQLException,
                      BugInPoolException,
                      DBIsDownException,
                      SomethingWrongInDriverException;


    It is very intersting to see how do you handle checked exeptions after evrycall. Do you rethrow more "abstract" exception wrapper again like "SomethingWrongInDAOException" ?
  34. Criticism is not FUD[ Go to top ]

    It is very intersting to see how do you handle checked exeptions after evrycall. Do you rethrow more "abstract" exception wrapper again like "SomethingWrongInDAOException"
    All I can do is refer you to the Javadoc documentation of our product. Please take a close look at kernel, configuration, and cache services. I singled out those services because they use both, checked and runtime exceptions.

    Here is the link:
    http://www.fitechlabs.com/javadoc/index.html

    I believe that our product demonstrates a proper balance between use of checked and unchecked exceptions.

    Looking forward to any feedback...

    Dmitriy.
    xTier team.
  35. Criticism is not FUD[ Go to top ]

    How do you recommend to hanle CacheException if CacheTxListener thorws it on transaction start ? Do I need to try later, core dump or to rethrow it as "CacheException" ? Is it some way to continue transaction if I say I want to abort it in callback myself ?
  36. Criticism is not FUD[ Go to top ]

    How to handle it if register no callback ?
  37. Criticism is not FUD[ Go to top ]

    Juozas:
    How do you recommend to hanle CacheException if CacheTxListener thorws it on transaction start ? Do I need to try later, core dump or to rethrow it as "CacheException" ? Is it some way to continue transaction if I say I want to abort it in callback myself ?
     
    How to handle it if register no callback?
     
    Firstly I would like to thank you for actually taking a look at the API. It seems to me that you are extremely biased against checked exceptions, but I will try to answer your question anyway...
     
    I believe that you are referring to Cache.startTx(...) method.
     
    Before I begin, I would like to note that this method also throws IllegalStateException which is a runtime exeption thrown in case if transaction already exists (just to make it clear that we _do_ actually use runtime exceptions).
     
    Now about CacheException. As you correctly noted for this particular method, CacheException is thrown if registered CacheTxListener throws an exception, so you are forced to somehow handle it (catch, rethrow, wrap-and-rethrow) even if you don't register the listener.
     
    Note that in most cases application does not care about the cause of Cache failure, but rather it cares about the fact that failure did occur. So in most cases error handling will be identical whether exception was thrown by listener or by cache internals. If CacheException thrown from the listener requires special handling, user can always subclass it, so it can be caught and properly handled.
     
    Also note that unless you are catching java.lang.Exception somewhere in your main method and handle all exceptions in the same manner (which is generally a bad practice), you will want to handle CacheException locally before you propagate it further. For example you may want to close database connections or send a message to admin. Having CacheException as checked exception at least gives you a compile time reminder that cache operation may fail and you should properly handle it. Note that handling exceptions doesn't always mean _recovery_, sometimes it simply involves gracefully releasing all resources before propagating exception further.
     
    If CacheException was a runtime exception, user of the API could potentially forget to handle it which would lead to broken error handling of the application. Furthermore, on any large scale project with more than a couple of developers it is _guaranteed_ that people will forget to handle runtime exceptions. That’s why vast majority of runtime exceptions (except for a few cases) should represent bugs in the code, and vast majority of checked exceptions should represent failures that can occur in production.
     
    As a last point, I would like to also bring your attention to our JCache API which is identical to Cache API, but also extends java.utils.Map interface. So if you are not happy with Cache API throwing checked exception, you can always use JCache API which throws runtime JCacheException.
     
    Bellow is the code sample slightly altered from example code that we ship with our product which demonstrates the ease of use of the Cache API. Note that CacheOrder and CacheKey are totally arbitrary objects. Also note that all SQL logic is implemented within CacheTxListener implementation. Complete version of the example is available with our product which can be downloaded from our website (xTier™).
     
        /**
         * This exmaple demonstrates a sample use of cache service.
         */
        private static void example() throws ExampleException {
            // 1. Get a handle on default cache instance.
            Cache cache = XtierKernel.getInstance().cache().getCache();
     
            CacheTx tx = null;
            
            try {
                // 2. Start serializable cache transaction.
                tx = cache.startTx(CacheTx.SERIALIZABLE);
                
                // 3. Retrieve single orders from cache.
                CacheOrder order1 = (CacheOrder)cache.get(new CacheKey(1, 1));
                CacheOrder order2 = (CacheOrder)cache.get(new CacheKey(1, 2));
                CacheOrder order3 = (CacheOrder)cache.get(new CacheKey(2, 3));
                
                // 4. Retrieve query result from cache.
                List orders = (List)cache.get(new CacheKey(1, "user_id=1 and qty > 5"));
                
                // 5. Update single order.
                CacheOrder newOrder = new CacheOrder(1, 1, 5);
     
                cache.put(new CacheKey(1, 1), newOrder);
     
                // 6. Update collection of orders.
                // Note that since we don't know the outcome of the update,
                // we simply store 'null' into cache. The query will be reloaded
                // from data storage on the next get operation.
                cache.put(new CacheKey(1, "qty=7", "user_id=1 and qty > 5"), null);
                
                // 7. Prepare cache transaction.
                tx.prepare();
                
                // 8. Commit cache transaction.
                tx.commit();
            }
            catch (CacheTxOptimisticLockException e) {
                // Some implementations may choose to retry the transaction whenever
                // optimistic lock failure happens. For simplicity sake here we
                // simply log it.
                logger.warning("Cache optimistic lock failure occurred.", e);
                
                assert tx != null;
                
                // 9. Rollback cache transaction.
                rollbackTx(tx);
            }
            catch (CacheException e) {
                // 10. If transaction was started, roll it back.
                rollbackTx(tx);
     
                throw new ExampleException("Unexpected cache error.", e);
            }
        }
     
    Hope this helps,
    Dmitriy
    xTier team.
  38. Criticism is not FUD[ Go to top ]

    I believe client code must look like this:

    public void example( Cache cache ){

    // 3. Retrieve single orders from cache.
                CacheOrder order1 = (CacheOrder)cache.get(new CacheKey(1, 1));
                CacheOrder order2 = (CacheOrder)cache.get(new CacheKey(1, 2));
                CacheOrder order3 = (CacheOrder)cache.get(new CacheKey(2, 3));
                
                // 4. Retrieve query result from cache.
                List orders = (List)cache.get(new CacheKey(1, "user_id=1 and qty > 5"));
                
                // 5. Update single order.
                CacheOrder newOrder = new CacheOrder(1, 1, 5);
     
                cache.put(new CacheKey(1, 1), newOrder);
     
                // 6. Update collection of orders.
                // Note that since we don't know the outcome of the update,
                // we simply store 'null' into cache. The query will be reloaded
                // from data storage on the next get operation.
                cache.put(new CacheKey(1, "qty=7", "user_id=1 and qty > 5"), null);

    }

    If you will write 100 this kind of methods you will see very big difference. I use generic way to handle exeptions in 99 of 100 cases, exceptional case is not a problem, I will not forget to handle it, if this is exceptional case. The same is about transactions, I need transactions or I do not need any transactions, I start, commit and abort transactions in the same way (in 99 of 100 cases).

    BTW, I think if cache fails and I do not know way then I must not try to find
    "better" way at runtime, it can have side effect and I prefer just core dump, I helps to fix problems not to hide problems.
  39. Criticism is not FUD[ Go to top ]

    If you will write 100 this kind of methods you will see very big difference. I use generic way to handle exeptions in 99 of 100 cases, exceptional case is not a problem, I will not forget to handle it, if this is exceptional case.
    I don’t need to write a hundred of these methods to see that no one would have any clue as far as what exception your method throws. How do you expect anyone (or yourself) to catch and handle correct exceptions?
    The same is about transactions, I need transactions or I do not need any transactions, I start, commit and abort transactions in the same way (in 99 of 100 cases).
    Nothing prevents your from doing it with checked exceptions (keep in mind that you were looking at example code and of course you would make changes in your application).
    BTW, I think if cache fails and I do not know way then I must not try to find
    "better" way at runtime, it can have side effect and I prefer just core dump, I helps to fix problems not to hide problems.
    Again, you can have the same logic for all cache starts, commits, rollbacks, and exceptions if you would like. Just move out this logic into a separate method. Since when adding a throws clause to your method became too much work? As far as core dump in production application - well... I have a different opinion.

    Regards,
    Dmitriy.
    xTier team.
  40. Criticism is not FUD[ Go to top ]

    There is nothing very bad with checked exeptions and runtime exceptions and it is more mater of taste, I prefer not to dublicate code, but checked exeptions makes me add some noisy declarations to interfaces or to break stack traces with exception wrappers. Probably it is possible to find a good use case for checked exeptions, but I have never saw it in practice. I hope your example was Cache API demonstration, if it is a recomendation for infrastructure error handling then I think this example is very bad (antipattern).
  41. Criticism is not FUD[ Go to top ]

    Sorry, probably I need to explain why this example is broked before to say "bad" and "antipattern", it can be not very clear in this context.

    You have tried to put all aspects to single method, if we will try to solve this problem (duplication) we will see how checked exeption "helps". Asume we have 100 methods or commands (It is very realistic), there is nothing to design and to talk about trivial use cases. There are a lot of ways to reduce duplication, but I will use commands and delegation (It is very common for servlet or messaging code).

    interface Command {

      void execute();

    }

    abstract class AbstractCommand{

      public final void execute(){

       try{

         //start transaction

          doExecute();

         //commit

        }catch(Throwable t){
          // abort
          // report error (core dump)
        }finally{
          // release resources
        }

      }

      protected abstract doExecute();
     
    }

    I do not need to declare noisy Exceptions and it is always safe to throw any exception from doExecute without wrappers (it breaks error diagnostic).

    I solve this problem this way at this time:


    interface Command {

      void execute()throws Throwable

    }


    And I do not think somebody can recommend better workaround for this JAVA flaw.
  42. Criticism is not FUD[ Go to top ]

    If you want command implementation then it can be command to parse XML file in JMS listener and to populate database, I will need to fight with JMSException,SAXException,IOException and SQLException, realistic use case, is not it ?
  43. Like Spring?[ Go to top ]

    It’s understandable that Rod Johnson was blinded by Servlet JSR participation and that’s where I guess this "idea" came from, but to this day assume that all development should conform to JSP container is just silly at best. Regards,Nikita Ivanov.
    What leads you to think that I arrived at my views on checked and unchecked exceptions from my participation in the Servlet 2.4 Expert Group?? If you read the discussion on exceptions in Chapter 4 of Expert One-on-One J2EE Design and Development I explain my reasoning in detail. You don't agree with my conclusions, and that's your right. (Until you start calling other projects "seriously flawed" simply because they don't conform to your personal views.) But the arguments are nothing whatever to do with JSP or servlets.

    Btw, what about other data access APIs besides Spring that use unchecked exceptions? Like TopLink and JDO, for example. Do you think that they were also motived by JSP?

    Rgds
    Rod
  44. Like Spring?[ Go to top ]

    Isn't exactly what Spring provides?
    Yes. Spring provides a sophisticated hierarchy of exceptions. With the important bonuses that:

    - Spring's data access exception hierarchy is not JDBC specific. Key concepts (such as data integrity violation) are common to any backend. We have JDBC-specific subclasses, but it's better not to have to program to them, to be able to code truly portable DAO interfaces, that don't depend on a specific persistence API.
    - The exception translation mechanism is extensible.

    Rgds
    Rod
  45. Exception chaining in JDBC[ Go to top ]

    Jonathan Bruce, JDBC 4.0 spec lead, has written up his thoughts on allowing SQLException to take a Throwable, allowing easy exception chaining.
    Hurrah!!
    (About bleeding time!)

    Constructor-based exception chaining has only been around in J2SE for about 3 years or so.... and was a common practice before that...

    Why is it that all of the J2EE Exception classes havent been changed ages ago? (NB: Dont need 1.4 to do it...)

    I wonder how long it will take for JMS spec to follow suit...
    looking to provide a limited set of exceptions that relate directly to SQL State definitions.
    Double-hurrah.

    -Nick
  46. I wonder how long it will take for JMS spec to follow suit...
    Still did not find an explanation what is wrong with constructor inheritance and why it is not allowed in Java.
  47. If that's not FUD...[ Go to top ]

    The way Spring forces developers to rely on runtime semantic in dealing with JDBC related code is probably most dangerous hole in Spring design (among many others not so serious)
    "Among many others"?

    If that's not FUD, nothing is...
  48. Unified exception codes[ Go to top ]

    What I really dislike on JDBC is that there are no shared error codes. If you want your code to be portable, you have no way how to find out the type of exception. For example that some constraint is broken (duplicate key) etc.

    I'd love to see SqlErrorCodes.java that defines codes for common issues and that is the property of SqlException.
  49. Unified exception codes[ Go to top ]

    "SQLstate" string, which follows the XOPEN SQLstate conventions. The values of the SQLState string are described in the XOPEN SQL spec.
    Probably there are too many constants to define or XOPEN SQL spec is too expensive to buy :)

    I hope it will be documented in JDBC spec. if there are some copyrigth problems with XOPEN then JDBC can define error codes itself. JDBC is used for JAVA only in practice and more generic standard for error codes is cool, but not very usefull for JDBC programmers.
  50. Unified exception codes[ Go to top ]

    I hope [SQL State codes] will be documented in JDBC spec. if there are some copyrigth problems with XOPEN then JDBC can define error codes itself.
    Amen. Currently a lack of clear unified exception codes is a major gap in the JDBC API. SQLState codes are not included in JDBC documentation, are pretty coarse-grained anyway (vendor codes provide much more detailed information), and not all JDBC drivers seem to return the correct SQLState code. I was quite surprised way back when I realised that the SQLState codes were not documented with JDBC, and that effective error handling often required database-specific code matching: not the portability JDBC aims for.

    That's part of the motivation for Spring's exception translation. It means that developers do not depend on database-specific error codes: the translation is done by the framework. Spring uses vendor codes to drive the translation, and falls back to SQLState only if the vendor code is unrecognized or 0.
  51. ...is that programmer errors, such as invalid SQL syntax, are thrown as exceptions derived from RuntimeException while environmental errors, such as the database going down, are thrown as checked exceptions.
  52. ...is that programmer errors, such as invalid SQL syntax, are thrown as exceptions derived from RuntimeException while environmental errors, such as the database going down, are thrown as checked exceptions.
    Actually, I would go the other way around. I could (maybe) recover from a SQL syntax error, not from a down Database.

    I would certainly not want to check for Database status with every call...

    Frankly, I don't get it with checked exceptions. You CAN catch every runtime exceptions if you want, anyway... IMHO, it's not a "dangerous hole"...

    I'm using Spring every day and it's an amazing framework. Period.