How to convert into error handling~

how to convert if (!(istringstream (s) >> n )) that part into error handling try throw catch format?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int main() {
  string s; // input as string.
  int n;  // input as int.
  cout << "Enter a positive integer or 0: ";
  cin >> s;

  if (!(istringstream (s) >> n))
    cout << "Error: You input string \"" << s << "\".\n"
         << "Input must have positive integer or 0 only.\n";
  else if (n < 0)
    cout << "Error: You input negative integer " << n << ".\n"
         << "Input must have positive integer or 0 only.\n";
  else {
    long long result = 1;
    for (int i = 1; i <= n; i++)
      result *= i;
    cout << "Factorial(" << n << ") = " << result << endl;    
  }
}
http://www.cplusplus.com/reference/ios/ios/exceptions/

you could create a `Natural' class with an overload operator<<
Topic archived. No new replies allowed.