CodeBlanks Logo Icon CodeBlanks

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.

Practice 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");.

Starter code

main.cpp
#include <iostream>
#include <string>

// Write the FileGuard class with RAII

int main() {
    // Create a FileGuard
    return 0;
}

Sample solution

main.cpp
#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;
}

Expected output

open: veri.txt
close: veri.txt

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 destructor cleanup

Question
class FileGuard { public: ____FileGuard() { /* close */ } };
Answer
class FileGuard { public: ~FileGuard() { /* close */ } };

Explanation: A destructor starts with ~ and releases the resource.

2 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 Correct answer
  • It supports multithreading

Explanation: With RAII the destructor is called via stack unwinding even on exceptions.

3 Match each piece to its role

Term Meaning
constructor Acquires resource
destructor Releases resource
stack unwinding Calls destructors
FileGuard File wrapper

All lessons in Advanced