https://rentry.org/PPP2_p355

// Code derived from Stroustrup's PPP2 book
// § 10.6 I/O error handling
//  -and beginning on p 355

#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

void error(const string s) { throw runtime_error(s); }
void error(const string s1, const string s2) { error(s1 + s2); }

//------------------------------------------------------------------------------

int main()
try {
  int i = 0;
  cin >> i;

  if (! cin) {
    // we get here (only) if an input operation failed:

    if (cin.bad())
      error("cin is bad");  // stream corrupted: let’s get out of here!

    if (cin.eof()) {
      // no more input
      // this is often how we want a sequence of input operations to end
    }

    if (cin.fail()) {  // stream encountered something unexpected
      cin.clear();     // make ready for more input

      // somehow recover . . .
    }
  }

} catch (exception& e) {
  cerr << "error: " << e.what() << '\n';
  return 1;

} catch (...) {
  cerr << "Oops: unknown exception!\n";
  return 2;
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_10/main_p355.cpp && ./a.out

PrevUpNext

Edit
Pub: 07 Apr 2023 22:04 UTC
Edit: 03 May 2023 09:48 UTC
Views: 390