C++ Винятки

2075 / C++ / Винятки


1.
try {
  int age = 12;
  if (age > 18) {
    cout << "OK";
  }
  else 
  {
    throw age; // or "404"
  }
}
catch (int a) 
{
  cout << "Error: " << a;
}
Error: 12

2.
try {
  int a = 1 / 0; // програма вилітає, catch - не спрацьовує
}
catch (int b) {
  cout << b;
}

 
3.
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
 

4. Вводити до коректного значення
#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);