views:

207

answers:

6

I have a Stack object being worked on by multiple threads. One of the threads is a worker thread which performs a pop operation on the Stack object. I wanted to handle the case where the Stack is empty and I see two options

try{
    Object obj = (Object) d_stackObj.pop(); 
   } 
catch (EmptyStackException e) 
   { ...}

OR

if( ! d_stackObj.empty() ) 
   Object obj = (Object) d_stackObj.pop(); 
else
   { ...}

My question is , which of the above is a better approach and why?

Thanks!

A: 

It is considered a bad practice to catch exceptions for the purposes of program flow. Use the latter method.

matt b
A: 

There is an overhead to creating the Exception. If it is easily avoidable, as it is in this case, why not avoid it?

There is a good O'Reilly article here that describes the uses of Exceptions. One key point (on the second page).

Never use exceptions for flow control

Rich Seller
+2  A: 

The second.

Exceptions are for unexpected program conditions and not business logic.

There might be also performance issues if you use exceptions for everything.

kazanaki
+3  A: 

I would think that the better approach would be to check if the stack is empty as in your second example.

Catching exceptions is costly!

The Sheek Geek
I wouldn't unduly worry about performance
Tom Hawtin - tackline
+1  A: 

Don't use Exceptions for Flow Control

Carl Manaster
+1  A: 

The second approach would work only if you have only one thread that can pop objects from your stack at all times.

If not, then your compound logic doesn't work correctly even though Stack itself is thread safe, as other threads may slice in between the empty() call and the pop() call. If you have more than one thread that may pop objects from your stack, you may need to do the following:

synchronized (d_stackObj) { // you must use the stack object as the lock
    if (!d_stackObj.empty()) { 
        Object obj = (Object)d_stackObj.pop(); 
    } else {
        ...
    }
}

The first approach does work even in this case as it uses a single atomic call.

sjlee
brilliant! I did not think of that. thanks!
rohangter