Why in the divisionNum
method after the throw
operator, the work of the try
block does not stop and does not proceed to the execution of the catch
block code, but quietly goes to the line cout << num1 / num2
?
#include <iostream> #include <string> using namespace std; class P { public: int num1, num2; P(int _num1, int _num2) { num1 = _num1; num2 = _num2; } void sumNum() { cout << num1 + num2 << endl; } void divisionNum() { if (num2 == 0) { throw "PPPPP"; } cout << num1 / num2; } ~P() {} }; int main() { setlocale(LC_ALL, "rus"); P obj2(10, 0); try { obj2.divisionNum(); } catch (string s) { cout << s << endl; return 1; } system("pause"); }
throw string("PPPPP");
will be caughtthrow string("PPPPP");
i.e. There is no implicit type conversion (fromchar*
tostd::string
). In general, it is a bad practice to throw an exception with a class that can generate it itself (I’mstd::string
aboutstd::string
), use the appropriate classes, for example,std::exception
. - StateItPrimitivecout << num1 / num2;
? - αλεχολυτ