#include <iostream>
#include <fstream>
#include <stdexcept>
class FileHandler {
private:
std::ofstream file;
public:
FileHandler(const std::string& filename) {
file.open(filename);
if (!file.is_open()) {
throw std::runtime_error("Unable to open file");
}
std::cout << "File opened" << std::endl;
}
~FileHandler() {
if (file.is_open()) {
file.close();
std::cout << "File closed" << std::endl;
}
}
void write(const std::string& data) {
file << data;
}
};
int main() {
try {
FileHandler fh("example.txt");
fh.write("Hello, World!");
// File is automatically closed when fh goes out of scope
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}