Обробка винятків

try {

     int age = 12;

     if (age > 18) {

          cout << "OK";

     }

     else {

          throw age;   // "404"

     }

}

catch (int a) {

     cout << "NO 18: " << a;

}

NO 18: 12

try {

     int a = 1 / 0;   // програма вилітає, catch - не спрацьовує

}

catch (int b) {

     cout << b;

}

int x = 3;

try {

     if (x == 0) { throw 'B'; }

     else if (x == 1) { throw x; }

     else if (x == 2) { throw 1.0; }

     else if (x == 3) { throw "Text1"; }

     cout << "\nEND";

}

catch (char c) { cout << "Char: " << c; }

catch (int i) { cout << "Int: " << i; }

catch (double d) { cout << "Double: " << d; }

catch (const char* s) { cout << "Char*: " << s; }

Char*: Text1

Вводити до коректного значення

#include <string>

    int opc;

    bool aux = true;

    cin.exceptions(istream::failbit);

    do {

        try {

            cout << "PLEASE INSERT VALUE:" << endl;

            cin >> opc;

            aux = true;

        }

        catch (ios_base::failure &fail) {

            aux = false;

            cout << "PLEASE INSERT A VALID VALUE" << endl;

            cin.clear();

            string tmp;

            getline(cin, tmp);

        }

    } while (aux == false);