Exception Handling & File I/O
C++ exceptions provide structured error handling with try/catch/throw. Unlike C error codes, exceptions automatically propagate up the call stack and work with RAII for guaranteed cleanup. File I/O uses stream objects (ifstream, ofstream) with the same << >> operators as cout/cin.
40 min•By Priygop Team•Last updated: Feb 2026
Exceptions & File I/O Code
Example
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
using namespace std;
// Custom exception
class FileError : public runtime_error {
string filename;
public:
FileError(const string &file, const string &msg)
: runtime_error(msg), filename(file) {}
const string &getFilename() const { return filename; }
};
// Function that throws
double divide(double a, double b) {
if (b == 0.0) throw invalid_argument("Division by zero");
return a / b;
}
void writeFile(const string &filename, const string &content) {
ofstream file(filename);
if (!file.is_open()) {
throw FileError(filename, "Cannot open file for writing");
}
file << content;
// File automatically closed by destructor (RAII)
}
string readFile(const string &filename) {
ifstream file(filename);
if (!file.is_open()) {
throw FileError(filename, "Cannot open file for reading");
}
string content((istreambuf_iterator<char>(file)),
istreambuf_iterator<char>());
return content;
}
int main() {
// Exception handling
try {
cout << divide(10, 3) << endl; // Works fine
cout << divide(10, 0) << endl; // Throws!
} catch (const invalid_argument &e) {
cerr << "Error: " << e.what() << endl;
}
// File I/O with exception handling
try {
writeFile("test.txt", "Hello, C++ File I/O!");
string content = readFile("test.txt");
cout << "Read: " << content << endl;
} catch (const FileError &e) {
cerr << "File error (" << e.getFilename() << "): " << e.what() << endl;
} catch (const exception &e) {
cerr << "Error: " << e.what() << endl;
}
return 0;
}