catching EmptyStackException vs. Testing is Stack is empty

exception, java, stack

Solution

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!

Problem

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!

Original source