String throwing exception
Solution 1:
I do not know what you are trying to experiment, but despite being allowed by the language, throwing objects that are not instances of (subclasses of) std::exception
should be avoided.
That being said you have a bunch of inconsistencies in your code.
First cin >> x.second;
will stop at the first blank character. So in your example you have only "1,"
in x.second
, so you test fails and you code does not throw anything.
You should ignore the newline left by cin >> x.first
and use getline
to read a full line include spaces:
P x;
cin >> x.first;
cin.ignore();
std::getline(cin, x.second);
The first try
block invokes UB, because you are declaring a new x
in that block that will hide the one you have just read. It should be:
try
{
//P x; // do not hide x from the enclosing function!
T(x);
}
Finaly, and even it is not an error you should always catch non trivial object by const reference to avoid a copy. Remember that exceptions are expected to be raised in abnormal conditions, and when memory becomes scarce you should avoid copy. But you must catch the exact same object that was thrown. So the second catch
should be:
catch (std::string exception)
{
std::cout << "\n" << exception;
}
or better (avoid a copy):
catch (const std::string& exception)
{
std::cout << "\n" << exception;
}