Let's say you have a piece of code like:
resource = allocateResource();
try { /* dangerous code here */ }
finally { free(resource); }
I'm not referring to any specific language here, but I guess Java, C#, and C++ would be good examples (assuming you're using __try
/__finally
in MSVC++).
Personally, I don't think this is exception-safe, because what if there's an exception before you enter the try
block? Then your resource will leak.
I've seen this enough times, though, that I think it I'm missing something... am I? Or is this really unsafe?
I'm not asking about allocateResource
throwing an exception, but a situation in which you get an exception after that function has returned, but before resource
is assigned.
I'm not asking about allocateResource throwing an exception, but a situation in which you get an exception after that function has returned, but before resource is assigned.
It gets very messy to try to handle this aspect of exception safety, not least because the language constructs don't allow you to install your finally handler in the middle of an assignment statement.
My rationale for all this is that if you can't get from the end of a function call to assigning to a variable then your system is already hosed. Who cares if you leak memory when you can't assign to a variable?