https://rentry.org/PPP2_p150

// Code derived from Stroustrup's PPP2 book
// § 5.6.3 Bad input
//  -and beginning on p 150

#include <iostream>
#include <stdexcept>

using std::cerr;
using std::cin;
using std::cout;
using std::runtime_error;

void error(const char* s) { throw runtime_error(s); }

double some_function()
{
  cout << "Please enter a float:\n";
  double d = 0;
  cin >> d;

  if (! cin)
    error("couldn't read a double in 'some_function()'");

  // do something useful . . .

  return d;
}

int main()
try {
  double func_res = some_function();

  cout << func_res << '\n';

} catch (runtime_error& e) {  // catch runtime errors
  cerr << "Exception: runtime error, " << e.what() << '\n';
  return 1;
}

build & run:

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

PrevUpNext

Edit
Pub: 23 Feb 2023 08:31 UTC
Edit: 29 Apr 2023 09:34 UTC
Views: 395