Java exceptions, exceptions, exceptions

Ovid on 2004-11-02T05:32:59

Frankly, I find avoiding duplicate code in Java to be a pain. I can't tell you how many times my perfectly sensible refactor has been tripped up by exception handling. I'd love to be able to pass around deferred bits of code. No such luck. In my database code, I seem to have a few sections of code that have identical try/catch blocks around them, but since the code on the inside of the try block is not the same, I can't seem to pull it out -- unless I wrap it in the try/catch blocks I'm trying to refactor. Am I just not getting the hang of software design in Java or is it always this bad?


unchecked exceptions

lachoy on 2004-11-02T13:09:04

Using unchecked exceptions for this helps a lot. Take a look at what the Spring Framework has done merging ORM and JDBC exceptions into a single unchecked hierarchy. Makes for very clean code, particularly if you use their *Template classes (JdbcTemplate, HibernateTemplate, ...).

Re:unchecked exceptions

Ovid on 2004-11-02T13:48:40

Er, are you saying that my design doesn't have a fundamental flaw? I find it hard to believe that a language is set up in such a way that I can't factor out common code.

Re:unchecked exceptions

lachoy on 2004-11-02T13:59:28

No, I'm just saying that one way around it is unchecked exceptions. I can't say one way or another about your design without actually seeing it :-) Unchecked exceptions can also be a way of sweeping problems under the rug.

But the Spring items I mentioned earlier are one way to get around these sorts of design issues even if you don't consider the unchecked exception part. There are a couple of examples at devx, and the Spring docs (esp. the PDF) are generally excellent and have examples as well. (See section 10.2 in the PDF for the JdbcTemplate info.)

Re:unchecked exceptions

Ovid on 2004-11-02T14:10:35

Oh, yeah, I didn't post a code snippet :) The essense of my problem is posted on Java Junkies. (I should really find a better site for posting Java stuff, I hate to admit.)

Re:unchecked exceptions

bazzargh on 2004-11-03T10:55:08

the better site?
http://codepaste.org/