The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Lecture/Lab #18
Error handling/exceptions, RAII
How do we check if reading from a stream was successful?
How do we reset the state of the input stream?
int read_with_error_checking(std::istream& in) {
int n;
if ( in >> n ) // check for errors
return n;
std::cout << "Error reading from stream\n";
return -1;
}
int main() {
std::cout << "Enter an integer: ";
int n = read_with_error_checking( std::cin );
if ( n != -1 )
std::cout << "You entered: " << n << "\n";
}
int read_with_error_checking(std::istream& in) {
int n;
if ( in >> n ) // check for errors
return n;
throw std::runtime_error("Error reading from stream");
}
Consider using std::optional if choosing this route.
In plain language, RAII simply means tying resource management to the object lifetime:
... where a resource could be almost anything that needs to be explicitly managed: memory, file handles, process handles, network sockets, database connections, mutexes, locks, etc.