claudius
claudius

Reputation: 1144

alternatives to exception handling for releasing resources

I have been learning about how to write exception safe code. Most of the practices suggested like RAII managed memory or mutexes are useful even when we are not using exceptions, as the programmer doesn't have to worry about managing resources manually.

But why do we need exceptions? When we don't get the resources we want, we cannot proceed further, and the process is going to terminate anyways. Then the operating system can worry about releasing the resources. So, what am I missing? what's wrong with my argument?

Upvotes: 0

Views: 58

Answers (1)

Jerry Coffin
Jerry Coffin

Reputation: 490108

You're taking for granted that the program can't proceed further when it lacks resources.

If letting the program simply die is an option, then you may not need exceptions. Then again, you might benefit from them even in such a case--throwing an exception lets things get cleaned up so (for example) files you've written will be flushed so you won't loose data that's still in buffers.

For quite a few more cases, just returning to the OS isn't an option. In quite a few cases you'd like to use a resource if possible, but you still need to continue processing even if it's not.

Upvotes: 2

Related Questions