...
Code Block | ||||
---|---|---|---|---|
| ||||
while (moreToDo) {
SomeType *pst = new SomeType();
try {
pst->processItem();
}
catch (...) {
// deal with exception
delete pst;
throw;
}
delete pst;
}
|
Handling resource cleanup in catch clauses does work, but can have several disadvantages:
- Each distinct cleanup requires its own try & catch blocks.
- The cleanup operation must not throw any exceptions.
Compliant Solution
A better approach would be to employ RAII. This forces every object to 'clean up after itself' in the face of abnormal behavior, preventing the programmer from having to do so. A judicious unique_ptr
would free the resource whether an error occurs or not.
...