C++
RAII and exceptions
Learn exception-safe resource management with RAII.
What is RAII?
RAII (Resource Acquisition Is Initialization) ties the lifetime of a resource to the lifetime of an object. The resource is acquired in the constructor and released in the destructor. Even if an exception is thrown, the destructor runs automatically.
Example: a FileGuard class that opens a file. The constructor opens the file, the destructor closes it. Even if the function throws, stack unwinding calls the destructor and the file is closed. This is far safer than calling close manually. In C++, std::vector, std::string and smart pointers are all written with RAII.
Stack unwinding
When an exception is thrown, stack unwinding begins: for each function on the call stack, destructors of local objects going out of scope are called. This continues until a catch block is reached.
Objects written with RAII are cleaned up automatically during this process. Example: if a function creates FileGuard f("a.txt"); and then throws, the destructor of f is called during unwinding and the file is closed. No manual finally block is needed. This is why C++ has no finally; RAII replaces it.
Exercise Write a FileGuard RAII class
Write a FileGuard class: the constructor takes a std::string and prints std::cout << "aç: " << name_ << "\n";; the destructor prints std::cout << "kapat: " << name_;. In main create FileGuard f("veri.txt");.
Show example solution
#include <iostream>
#include <string>
class FileGuard {
std::string name_;
public:
explicit FileGuard(const std::string& n) : name_(n) {
std::cout << "open: " << name_ << "\n";
}
~FileGuard() {
std::cout << "close: " << name_;
}
};
int main() {
FileGuard f("veri.txt");
return 0;
}
Test yourself
-
destructor cleanup
class FileGuard { public: ____FileGuard() { /* close */ } };
Show answer
class FileGuard { public: ~FileGuard() { /* close */ } };
-
What is the advantage of RAII in exception safety?
- It makes the code faster
- It uses less memory
- It releases the resource automatically even on exceptions
- It supports multithreading
Show answer
It releases the resource automatically even on exceptions — With RAII the destructor is called via stack unwinding even on exceptions.
-
Match each piece to its role
- constructor
- Acquires resource
- destructor
- Releases resource
- stack unwinding
- Calls destructors
- FileGuard
- File wrapper
Next lesson: std::expected