← Back to C++ Course | Chapter 15: File I/O | Lesson 5 of 6

C++ File Error Handling

File error handling is checking whether opening, reading, or writing a file worked, like making sure a door opened before walking in. Streams have flags that tell you what went wrong.
Syntax
cpp
std::ifstream file_name("filename.txt");

if (file_name.fail()) {
  // could not open or read
}

file_name.clear();  // reset error flags

Stream State Flags

Every stream maintains internal state flags that record what happened during the last operation: eof() reports whether the stream has reached the end of the file, while fail() reports a more general failure, such as expecting a number but finding text.

Example: Stream State Flags

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ifstream file("nonexistent.txt");
	// Print to the console with cout
	std::cout << "eof=" << file.eof() << " fail=" << file.fail() << std::endl;
	// Return 0 to signal that the program finished successfully
	return 0;
}

Clearing Stream Flags

Once any error flag is set, a stream refuses to perform further operations, even if the underlying problem is temporary or already resolved -- calling clear() resets those flags back to a working state so you can continue using the stream (for example, after handling a bad line of input).

Example: Clearing Stream Flags

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ifstream file("nonexistent.txt");
	// Check whether file.fail()
	if (file.fail()) {
		// Print to the console with cout
		std::cout << "Error detected" << std::endl;
		file.clear();
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Handling Missing Files

Attempting to open a file that doesn't exist doesn't throw an exception by default -- it just leaves the stream in a failed state.

Checking is_open() or the stream's boolean state immediately after opening catches this before you try to read uninitialized or garbage data from a stream that was never actually connected to a file.

Example: Handling Missing Files

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ifstream file("nonexistent.txt");
	// Check whether !file.is_open()
	if (!file.is_open()) {
		// Print to the console with cout
		std::cout << "File does not exist" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Writing Errors

A write can fail for reasons that have nothing to do with your code, such as a full disk or a read-only filesystem.

Checking good() after a write confirms none of the error flags (eof, fail, or bad) are set, giving you confidence the data was actually written rather than silently dropped.

Example: Writing Errors

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ofstream file("data.txt");
	file << "Some content";
	// Check whether file.good()
	if (file.good()) {
		// Print to the console with cout
		std::cout << "Write confirmed successful" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Exception Handling with Files

Calling stream.exceptions() with the appropriate flags configures a stream to throw a std::ios_base::failure exception instead of just silently setting a flag when an error occurs -- this lets you handle file errors with the same try/catch structure you'd use for other exceptional conditions in your program.

Example: Exception Handling with Files

cpp
// Include std::cout and std::cin
#include <iostream>
// Include file streams
#include <fstream>

// Program execution starts in main()
int main() {
	std::ifstream file;
	file.exceptions(std::ios::failbit);
	// Try code that might throw an exception
	try {
		file.open("nonexistent.txt");
	// Handle the exception if one was thrown
	} catch (std::ios_base::failure &e) {
		// Print to the console with cout
		std::cout << "Exception thrown for file error" << std::endl;
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Not checking stream state flags after reading.
  2. Forgetting to call clear() before reusing a stream after an error.
  3. Assuming the file exists without checking is_open().
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.