Let's have a piece of code (fstream is just an example, we could be talking about dynamic memory allocation...):
fstream f;
try {
f.open("xxx");
...
f.close();
} catch (...) {
...
}
When something goes wrong I would like to close() the file (release memory or whatever), but I don't know the state of f. After all, the exception may come from f.open(). I don't think it would be safe to call f.close() in the catch clause as I can no longer believe f.
f could also be a pointer to a dynamically allocated array which I would like to delete [], but who knows where it points to after the exception was thrown...
This may not be very common, but what can I do when I absolutely can't affort any additional damage?
I can think about an immediate abort().
Thanks.
You should use RAII or popularly known here as SBRM (Scope Based Resource Management) :)
fstream
destructors call close
for you. When an exception is thrown, the file is closed automatically.
For managing memory, you can use smart pointers.
For managing mutexes or more general locks, most libraries provide you with a class whose destructor unlocks the mutex for you.
Never write code in the form:
acquire a resource
do stuff which can throw
release a resource
Instead, use objects whose destructors release the resource for you.
The fstream destructor will call close() for you, so you don't really need to close it yourself (unless you want to see the return code of close()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With