The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Exceptions in Java, re-throw and finally ??

Hi
I'm puzzled by the way exceptions are supposed to work (don't get me started on how much I loathe exceptions, but sometimes you have no choice but to use them).

The literature says that when you're in a catch block you can rethrow the current exception, or event throw another one, and that's so cool. They even give those nice examples that nobody would ever need in real life.

The literature also says that the Java designers in their infinite wisdom have thought about when you need to free resources, creating the finally clause.

Apparently you can't do BOTH can you ??

I have

Resource r1 = null;
Resource r2 = null;
try
{
  r1 = openResource1();
  r2 = openResource2(); // could throw

  DoStuffThatMightThrowAnException();
 
}
catch( Exception e)
{
  // I would like to rethrow e here so that

}
finally
{
  if( r1 != null ) r1.close();
  if( r2 != null ) r2.close();
}
28 Projects Later Send private email
Tuesday, May 20, 2008
 
 
sorry... hit the wrong button and my post was incomplete!

I want to rethrow e from the catch block so that the caller can get it.

But if I do that, the finally won't get executed.

So what should I do ? All I want is my resources closed and my caller notified. Should be pretty basic no ?

It really gets on my nerves that all those Java-is-so-cool books give you tons of cute examples with Cat and Dog classes, and they never tell you how to do something useful.

Or maybe I'm the one who doesn't get it ? If I'm stupid, tell me, I can handle it... Fire away...

Thanks
28 Projects Later Send private email
Tuesday, May 20, 2008
 
 
> the finally won't get executed
why not?
Joe
Tuesday, May 20, 2008
 
 
The finally block will be called. Just try it in a simple example.
Jeff Hawkins
Tuesday, May 20, 2008
 
 
Ok.... for some reason I messed up my previous test.. I did it again and, yes, the finally does get executed. How could I miss that.

Sorry sorry sorry ...

So I am indeed stupid, it's now official.
On the plus side, I hear that that can help you get laid more. Well I guess I'm off to the bar !

My apologies again, and Java is a great language that has many wonderful books written about it.
28 Projects Later Send private email
Tuesday, May 20, 2008
 
 
You typically don't want to rethrow exceptions unless you intend to actually do something with them first. Rethrowing an exception can sometimes lead to losing information in your stacktrace. Your catch block should never just say:

catch (Exception ex)
{
    throw ex;
}

In this case just use a try-finally block instead and let the exceptions bubble up to be handled by code that can actually do something about them.

But that's just my two cents. Don't even get me started on the evils of Java checked exceptions. Google for "checked exceptions are evil" and you'll see what I mean.
dood mcdoogle
Tuesday, May 20, 2008
 
 
@dood mcdoogle

I do not see your point or other peoples point of "checked exceptions are evil"

Checked exceptions are a way to force onto the caller as part of the contract between the caller and the callee what runtime errors will be handled. It's as simple as that.

Its just a pointless rant really, the problem is that the debate about exceptions checked or unchecked is not about exceptions but how people THINK error propagation should occur between different modules.

The other problem, is that because of Java/C#/C++ and the cluster **** of different acronym and meaning behind them in each programing language. You have no idea if the person is talking from a C++ perspective where exceptions are exceptional. Or C# where they're not checked, then finally java where they're checked. Then to add on top of that is the design philosophy of each framework.

And yes, some design philosophy's will allow you to design more solid working code, and others will leave you with a memory dump. Either one is valid depending on the persons perspective and background.
Entity Send private email
Wednesday, May 21, 2008
 
 
Don't know about java but in C# you can do
catch (Exception ex)
{
    // do some logging here
    throw; // notice no ex
}

This will preserve the original exception and the stacktrace.
job seeker
Wednesday, May 21, 2008
 
 
"Its just a pointless rant really, the problem is that the debate about exceptions checked or unchecked is not about exceptions but how people THINK error propagation should occur between different modules."

Agreed. It really is just a pointless rant because there is no "right" answer. You've summed it up nicely by basically pointing out that it is a matter of taste. I prefer to have exceptions caught in a more centralized location. I like API's to throw exceptions and have client code simply let them bubble up to a "user process" layer that controls the state machine and can actually do something about them. Java checked exceptions don't facilitate this because they require me to declare them all the way up the chain which can lead to the typical application of the following two patterns:

1) Just declare that all methods throw the generic exception type.

2) Swallow all exceptions.

Neither of these is a good solution. There are other solutions as well (throwing Errors, etc.). But again, these are less than optimal.

There is no reason to debate the value of checked exceptions here since it has been done ad nauseum on the Internet already. But clearly you can tell which side of the fence I sit on.
dood mcdoogle
Wednesday, May 21, 2008
 
 
I found this highly useful:

http://www.sanabel-solutions.com/content/view/21/

Learning how to design a proper exception handling framework takes some time, but it is worth it.
Ryan
Wednesday, May 21, 2008
 
 
Ryan,

That sanabel link is great reading. I'd never seen such a practical discussion of how to organize exception handling in a real life size application.

Very useful, thanks ! I owe you a beer.
28 Projects Later Send private email
Wednesday, May 21, 2008
 
 
@dood mcdoogle

Yes, I can see which side of the fence you sit. Was just calling out that 'checked or unchecked' exceptions is just a flame bait that doesn't really help to progress the discussion.

My preference is for findings design techniques to help uncover programing errors and mistakes early on in the development cycle. The clear separation between the filter modules and the core system.

One thing I do find lacking with a lot of material and also the web site link posted above. Is there is not a very clear distinction between the core system and the error checking. I find that people, especially young people cannot separate between both of them where its virtue you do so early on in the project.

Instead new developers start using exceptions in all parts of the code to make up for uncertainly about what exactly this module is suppose to do. This is why, I said more attention needs to be giving to the design and what you as a developer considers a runtime error or programming error. This is where the problem begins, because there is no silver bullet and people have different perspective from different backgrounds.

This is the reason why it all comes down to design and experience. Code is just code.
Entity Send private email
Wednesday, May 21, 2008
 
 
Well Entity, I guess I understand where you are coming from. But we will have to agree to disagree. I don't know why I would want to spend more time analyzing types of errors during the design phase when the reality is that you can't account for all of the types of errors that can possibly occur. Sometimes it seems better to just use a more centralized exception handling technique with the understanding that regardless of the type of error we must be ready to handle the fact that an error can occur at any time. There are certainly times when you want to program to specific error scenarios (if you can recover from them). But that is not usually the norm in my experience.

So I agree that it is a matter of perception and taste. And we clearly have different tastes.  ;)
dood mcdoogle
Wednesday, May 21, 2008
 
 
dood: With regards to the solutions you proposed, wouldn't a better solution be to simply catch the checked exception and re-throw it as a wrapped runtime exception. For example:

try {
    ... do some IO Work Here
} catch (IOException e) {
    throw new MyApplicationRuntimeException(e);
}

My applications tend to follow the same methodology as yours with respect to handling exceptions centrally and the above works quite well for me. Using this technique my code doesn't have to keep catching exceptions through the various layers of code.
Gerald
Thursday, May 22, 2008
 
 
Gerald: Yes, that is an alternative. We usually just catch exceptions and thrown Errors which have the same effect as RuntimeExceptions. But it's not a practice that we like to use regularly. We mostly use it for legacy code where a programmer is specifically swallowing exceptions pretty far down in the code and we need to get them to bubble up without changing every single call point up the chain.
dood mcdoogle
Thursday, May 22, 2008
 
 
>> This will preserve the original exception and the stacktrace. <<

True, but it also terminates the first pass of exception handling. This is true for NET, I don't know about Java. When you try to debug this, you'll find the debugger stops on the re-throw rather than the original throw. That means you've lost the original context and state, which can mean a miserable debugging experience.

This is inevitable in a few cases, such as when a managed exception crosses an AppDomain boundary. Then the CLR will marshal and do a re-throw anyway. But you should avoid this as much as possible in application code.

The article linked to by Ryan is quite interesting. But its treatment of assertions is rather unusual. Most people do not use assertions for defensive programming!
Mark Pearce Send private email
Saturday, May 24, 2008
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz