JSTAcademy
0 XP
Dashboard
Crash Courses
File I/O & Exception Handling
40 min
PhD+195 XP
Crash Courses · PhD

File I/O & Exception Handling

Read and write files, throw and catch typed exceptions
40 min read+195 XP on completionCert: C++ Crash Course
Tap any word in the text below to start reading from there.

File I/O & Exception Handling

Reading a File Line by Line

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream file("data.txt");

    if (!file.is_open()) {
        std::cerr << "Error: could not open data.txt" << std::endl;
        return 1;
    }

    std::string line;
    while (std::getline(file, line)) {
        std::cout << line << std::endl;
    }

    file.close(); // optional — destructor closes it automatically
    return 0;
}

Writing to a File

std::ofstream out("output.txt");
if (!out) {
    std::cerr << "Cannot open output.txt" << std::endl;
    return 1;
}

out << "Line 1\n";
out << "Line 2\n";
// file closed by destructor

Appending

std::ofstream log("app.log", std::ios::app);
log << "[INFO] Server started\n";

Exception Handling

#include <stdexcept>

double safeDivide(double a, double b) {
    if (b == 0.0) {
        throw std::invalid_argument("Division by zero");
    }
    return a / b;
}

int main() {
    try {
        double result = safeDivide(10.0, 0.0);
        std::cout << result << std::endl;
    }
    catch (const std::invalid_argument& e) {
        std::cerr << "Caught: " << e.what() << std::endl;
    }
    catch (const std::exception& e) {
        std::cerr << "Std exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cerr << "Unknown exception" << std::endl;
    }
    return 0;
}

Exception Hierarchy

std::exception
  ├── std::logic_error
  │     ├── std::invalid_argument
  │     └── std::out_of_range
  └── std::runtime_error
        ├── std::range_error
        └── std::overflow_error

Catch by const reference to avoid slicing and unnecessary copies.

Custom Exceptions

class FileError : public std::runtime_error {
    std::string path;
public:
    FileError(const std::string& path, const std::string& msg)
        : std::runtime_error(msg), path(path) {}

    const std::string& getPath() const { return path; }
};

void readConfig(const std::string& path) {
    std::ifstream f(path);
    if (!f.is_open()) {
        throw FileError(path, "Cannot open config file: " + path);
    }
    // ...
}

RAII + Exceptions

Because destructors always run — even during stack unwinding from an exception — RAII-managed resources are always released:

void process() {
    std::ifstream file("data.txt"); // RAII — file closed no matter what
    auto lock = std::lock_guard<std::mutex>(mtx); // RAII — unlocked no matter what
    // if an exception is thrown here, file and lock are still cleaned up
}
0%