Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Safe Exception Handling

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.

like image 641
Petr Avatar asked May 13 '11 11:05

Petr


3 Answers

You should use RAII or popularly known here as SBRM (Scope Based Resource Management) :)

like image 182
Alok Save Avatar answered Nov 11 '22 21:11

Alok Save


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.

like image 10
Alexandre C. Avatar answered Nov 11 '22 21:11

Alexandre C.


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()).

like image 4
Bo Persson Avatar answered Nov 11 '22 20:11

Bo Persson