1. Goals
Choose how to report an expected refusal or an operation that cannot finish.
Track resource cleanup after
throw, including constructor failure.Distinguish releasing a resource from undoing changes already made.
2. Prerequisites
You know classes, constructors, destructors, members, ownership, and RAII.
You have also used bool to reject a request without changing data.
This lesson adds try, throw, catch, and two error types from <stdexcept>.
3. Explanation
A report export needs the only processing slot. JobSlot keeps the
free/busy state. tryAcquire() returns false when already busy and leaves
the state unchanged. This is an expected outcome the caller can handle
immediately with if. The example models a slot without creating files
or connecting to a service.
SlotGuard must acquire the slot to become a valid object. If acquisition
fails, its constructor uses throw std::runtime_error("slot busy").
throw stops the current path and looks for a matching catch; remaining
statements on that path are skipped. It does not automatically retry.
ExportJob contains guard_, which is constructed before the constructor
body runs. If report data is invalid, the body throws
std::invalid_argument. Construction of ExportJob did not complete, so
its own destructor does not run. Its completed guard_ member is still
destroyed and releases the slot. This is why a resource belongs in a RAII
member rather than a raw handle that relies on the outer destructor.
When job.run(true) throws and control travels to the outer handler,
job leaves its scope and destroys guard_ before entering catch.
This process is stack unwinding: completed automatic local objects are
destroyed in reverse order as the error path exits their scopes. This is
not a promise that every way of terminating a program calls destructors.
catch (const std::exception& error) reads the error by reference;
what() supplies its message. Both std::invalid_argument and
std::runtime_error match this handler. Here invalid input prevents
construction, whereas the runtime error reports an unfinished operation.
These are choices made by the functions' contracts, not a rule that all
invalid input must cause an exception.
SlotGuard's destructor only calls the nonthrowing release().
noexcept explicitly promises that no exception will escape. Do not
report a new failure by throwing from a destructor while another error is
being handled; the program can terminate. If closing a real resource can
fail, provide an explicit close operation with a result to inspect while
keeping destructor cleanup safe.
slot must outlive every guard and job that borrows it. While a guard
holds the slot, only that guard should call release(); the caller must
not release it early. Copying is disabled so two objects cannot both take
responsibility for releasing the same slot. This is a single-threaded
example, not a lock for concurrent code.
After the run error, attempts is still 1. RAII released the slot but
did not decrement the counter: resource cleanup does not automatically
roll back all changes. Preserving data on failure requires deliberate
validation before mutation or an appropriate rollback strategy.
The C++ working draft describes destruction on the way to a handler and after failed initialization.
4. Runnable example
Compile as C++17. Input is fixed; no input or file creation is needed.
#include <exception>
#include <iostream>
#include <stdexcept>
class JobSlot {
bool busy_ = false;
public:
JobSlot() = default;
JobSlot(const JobSlot&) = delete;
JobSlot& operator=(const JobSlot&) = delete;
bool tryAcquire() noexcept {
if (busy_) {
return false;
}
busy_ = true;
return true;
}
void release() noexcept { busy_ = false; }
bool busy() const noexcept { return busy_; }
};
class SlotGuard {
JobSlot& slot_;
public:
explicit SlotGuard(JobSlot& slot) : slot_(slot) {
if (!slot_.tryAcquire()) {
throw std::runtime_error("slot busy");
}
}
SlotGuard(const SlotGuard&) = delete;
SlotGuard& operator=(const SlotGuard&) = delete;
~SlotGuard() noexcept { slot_.release(); }
};
class ExportJob {
SlotGuard guard_;
public:
ExportJob(JobSlot& slot, bool valid) : guard_(slot) {
if (!valid) {
throw std::invalid_argument("invalid report");
}
}
void run(bool fail) const {
if (fail) {
throw std::runtime_error("export failed");
}
std::cout << "Export finished\n";
}
};
int main() {
JobSlot slot;
std::cout << std::boolalpha;
{
SlotGuard guard(slot);
std::cout << "Acquire busy slot: " << slot.tryAcquire() << '\n';
}
std::cout << "Busy after scope: " << slot.busy() << '\n';
try {
ExportJob invalid(slot, false);
} catch (const std::exception& error) {
std::cout << "Constructor error: " << error.what() << '\n';
}
std::cout << "Busy after constructor error: " << slot.busy() << '\n';
int attempts = 0;
try {
ExportJob job(slot, true);
++attempts;
job.run(true);
} catch (const std::exception& error) {
std::cout << "Run error: " << error.what() << '\n';
}
std::cout << "Busy after run error: " << slot.busy() << '\n';
std::cout << "Attempts after error: " << attempts << '\n';
{
ExportJob retry(slot, true);
retry.run(false);
}
std::cout << "Busy after retry: " << slot.busy() << '\n';
return 0;
}Output:
Acquire busy slot: false
Busy after scope: false
Constructor error: invalid report
Busy after constructor error: false
Run error: export failed
Busy after run error: false
Attempts after error: 1
Export finished
Busy after retry: false5. Common mistakes
Putting
release()afterrun()and assuming it always runs;throwskips it.Expecting the outer destructor to fix a constructor that never completed.
Catching by value and losing information belonging to the derived error type.
Throwing from a destructor or marking a throwing function
noexceptto hide the problem; an exception escaping that function terminates the program.Assuming
catchor RAII restores the previous value ofattempts.Keeping a guard beyond
slot's lifetime or callingrelease()while held.
6. Practice
While one
SlotGuardis alive, construct another in atryblock. Expectslot busy. Aftercatch, the slot must still be busy because the first guard still holds it.Try
ExportJob(slot, false)three separate times. Each constructor error must leaveslot.busy()false; a later valid construction must work.Move
++attemptsafterjob.run(true). The counter now stays0after the error because the increment is skipped, not because RAII undoes it.In a scope containing
SlotGuard guard(slot), try addingSlotGuard duplicate{guard};. Compilation must fail because copying is deleted. Remove the line to restore the runnable example.
7. Self-check
Why is the slot released when
ExportJob's constructor throws? Answer: its completedguard_member is destroyed when outer initialization fails.ExportJob's own destructor need not run.Does
catchsee a free or busy slot after the error fromrun? Answer: free.joband its guard were destroyed on the way to the outer handler. A guard in a scope outside the handler would live longer.Why does
attemptsremain1after the exception? Answer: the increment completed beforethrow. The destructor releases the slot; it neither knows about nor rolls back the caller's counter.
Sample code
Source file
cpp98_foundation/17_errors_cleanup/main.cpp
#include <exception>
#include <iostream>
#include <stdexcept>
class JobSlot {
bool busy_ = false;
public:
JobSlot() = default;
JobSlot(const JobSlot&) = delete;
JobSlot& operator=(const JobSlot&) = delete;
bool tryAcquire() noexcept {
if (busy_) {
return false;
}
busy_ = true;
return true;
}
void release() noexcept { busy_ = false; }
bool busy() const noexcept { return busy_; }
};
class SlotGuard {
JobSlot& slot_;
public:
explicit SlotGuard(JobSlot& slot) : slot_(slot) {
if (!slot_.tryAcquire()) {
throw std::runtime_error("slot busy");
}
}
SlotGuard(const SlotGuard&) = delete;
SlotGuard& operator=(const SlotGuard&) = delete;
~SlotGuard() noexcept { slot_.release(); }
};
class ExportJob {
SlotGuard guard_;
public:
ExportJob(JobSlot& slot, bool valid) : guard_(slot) {
if (!valid) {
throw std::invalid_argument("invalid report");
}
}
void run(bool fail) const {
if (fail) {
throw std::runtime_error("export failed");
}
std::cout << "Export finished\n";
}
};
int main() {
JobSlot slot;
std::cout << std::boolalpha;
{
SlotGuard guard(slot);
std::cout << "Acquire busy slot: " << slot.tryAcquire() << '\n';
}
std::cout << "Busy after scope: " << slot.busy() << '\n';
try {
ExportJob invalid(slot, false);
} catch (const std::exception& error) {
std::cout << "Constructor error: " << error.what() << '\n';
}
std::cout << "Busy after constructor error: " << slot.busy() << '\n';
int attempts = 0;
try {
ExportJob job(slot, true);
++attempts;
job.run(true);
} catch (const std::exception& error) {
std::cout << "Run error: " << error.what() << '\n';
}
std::cout << "Busy after run error: " << slot.busy() << '\n';
std::cout << "Attempts after error: " << attempts << '\n';
{
ExportJob retry(slot, true);
retry.run(false);
}
std::cout << "Busy after retry: " << slot.busy() << '\n';
return 0;
}