Error Handling and State
Check stream state.
Error Handling and State is a free C++ Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the C++ Academy learning path, and your progress syncs across the web and the CoddyKit app. The C++ Academy course includes 4 lessons in total.
Stream State Bits
Every stream tracks its condition with state flags:
- goodbit: all is well.
- eofbit: end of file reached.
- failbit: a logical error (bad format).
- badbit: a serious I/O error.
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("missing_98765.txt");
std::cout << std::boolalpha << "good: " << in.good() << '\n';
return 0;
}Testing a Stream
A stream converts to bool: it is true when usable. if (!in) detects failure concisely.
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("nope_55555.txt");
if (!in) std::cout << "stream not usable\n";
else std::cout << "ok\n";
return 0;
}good, eof, fail, bad
Each flag has a query method: good(), eof(), fail(), and bad().
#include <iostream>
#include <sstream>
int main() {
std::istringstream s("abc");
int x;
s >> x; // fails: not a number
std::cout << std::boolalpha;
std::cout << "fail: " << s.fail() << '\n';
std::cout << "bad: " << s.bad() << '\n';
return 0;
}Failed Extraction
When >> cannot parse the expected type, it sets failbit and leaves the target unchanged.
#include <iostream>
#include <sstream>
int main() {
std::istringstream s("hello");
int n = -1;
if (!(s >> n)) std::cout << "could not read an int, n stays " << n << '\n';
return 0;
}Clearing State
Once a fail flag is set, the stream stays unusable until you call clear() to reset it.
#include <iostream>
#include <sstream>
int main() {
std::istringstream s("x 42");
int n;
s >> n; // fails on 'x'
s.clear(); // reset state
std::string word;
s >> word; // now reads 'x'
std::cout << "recovered: " << word << '\n';
return 0;
}Ignoring Bad Input
After clear(), use ignore() to discard the offending characters before retrying.
#include <iostream>
#include <sstream>
#include <limits>
int main() {
std::istringstream s("bad 100");
int n;
while (!(s >> n)) {
s.clear();
s.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
}
std::cout << "read " << n << '\n';
return 0;
}Distinguishing EOF from Error
After a read loop ends, check whether it was clean eof() or a real bad() failure.
#include <iostream>
#include <sstream>
int main() {
std::istringstream s("1 2 3");
int x;
while (s >> x) {}
std::cout << std::boolalpha << "reached eof: " << s.eof() << '\n';
std::cout << "hardware error: " << s.bad() << '\n';
return 0;
}Checking After Open
Always verify the stream right after opening a file so you fail fast on a missing or unreadable path.
#include <iostream>
#include <fstream>
int main() {
std::ifstream in("absent_11111.txt");
if (!in.is_open()) {
std::cout << "open failed, aborting\n";
return 1;
}
std::cout << "never reached\n";
return 0;
}Enabling Exceptions
You can ask a stream to throw on errors with exceptions(), turning silent failures into catchable std::ios_base::failure.
#include <iostream>
#include <fstream>
int main() {
std::ifstream in;
in.exceptions(std::ios::failbit);
try {
in.open("ghost_22222.txt");
} catch (const std::exception& e) {
std::cout << "caught open failure\n";
}
return 0;
}Validating Read Counts
After a binary read, gcount() reports how many bytes were actually read, letting you detect short reads.
#include <iostream>
#include <fstream>
int main() {
int v = 9;
std::ofstream("g.bin", std::ios::binary).write(reinterpret_cast<const char*>(&v), sizeof(v));
int out;
std::ifstream in("g.bin", std::ios::binary);
in.read(reinterpret_cast<char*>(&out), sizeof(out));
std::cout << "read " << in.gcount() << " bytes\n";
return 0;
}A Robust Read Loop
Combine the techniques: test the stream in the loop, then after it ends distinguish a clean finish from an error.
#include <iostream>
#include <sstream>
int main() {
std::istringstream s("5 10 15");
int total = 0, x;
while (s >> x) total += x;
if (s.eof()) std::cout << "sum = " << total << " (clean)\n";
else std::cout << "error during read\n";
return 0;
}Quick Check
Test your understanding of stream state.
Recap
You learned stream error handling:
- state flags good/eof/fail/bad, queried via their methods or by testing the stream as a bool
clear()resets state andignore()discards bad input- distinguish clean
eof()from real errors;exceptions()can throw, andgcount()validates binary reads
Next course: generating random numbers with <random>.
Learn C++ with an AI tutor — free
Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.
- Courses
- 51
- Lessons
- 203
Frequently Asked Questions
Is the “Error Handling and State” lesson free?
Yes — any 3 lessons of the C++ Academy learning path, including “Error Handling and State”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The C++ Academy course includes 4 lessons in total.
What will I learn in “Error Handling and State”?
Check stream state. You practise C++ Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C++ Academy?
No prior experience is required. C++ Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.
How long does the “Error Handling and State” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C++ Academy lesson?
Yes. Every C++ Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Reading Files with ifstream
- Writing Files with ofstream
- Binary File I/O
- Error Handling and State