Program defensively and use option 1.
Since the Stack class provides the ability to check whether it contains anything before trying to Pop a value from it, you should do the check and avoid using the exception for flow control.
If you want to avoid doing the if check throughout your application, you could create a TryPop extension.
public static class StackExtensions
{
public static bool TryPop<T>(this Stack<T> stack, out T value)
{
if (stack.Count > 0)
{
value = stack.Pop();
return true;
}
value = default(T);
return false;
}
}
It could be used in the following way:
T resource;
if (availableResources.TryPop(out resource))
{
// use `resource` for something
}
It's worth noting that this approach is only suitable if the Stack is not accessed concurrently! - If it is, and you are using .NET 4.0 onwards then you should use ConcurrentStack, otherwise create your own concurrent stack which encapsulates a Stack and manages access to it with locks.
DownloadRemoteFile(url)). Or for python. – avip Nov 15 '12 at 22:12