Create a program that demonstrates that a function with its own try block should not catch all possible exceptions thrown in the try block. Some exceptions may be issued to external scopes and processed into them.

I understand here it is necessary that when exiting the function there was another catch to handle another situation. Tell me how to implement it. There is syntactically wrong. Swears.

void Foo(int& a) { try { if (a > 0) throw 1; else throw "Digit is negative!\n\n"; } catch (int & res) { cout << "Digit is positive!\n\n"; } } void main() { int a; cout << "Enter digit:"; cin >> a; Foo(a); catch (char * res) { cout << *res << endl; } } 

Closed due to the fact that off-topic participants gil9red , VTT , Peter Samokhin , default locale , 0xdb Jul 25 '18 at 11:51 pm .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- gil9red, VTT, Peter Samokhin, 0xdb
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    Well, you wrote everything - in the function you intercept not everything that you generate (or you regenerate an exception in the catch block), and then you demonstrate from the outside that the exception went outside the limits of the function. With such a statement of the question - do it - you are on the verge of a foul - closing as an educational task, put on other people's shoulders :) - Harry
  • Something fails to be syntactically implemented - Sneikof
  • one
    Look carefully what VS2017 writes to you (if you work in it), as a rule, everything is clearly written where you have a problem. - LFC
  • The answer you have already given. Note, it is better not to throw as exceptions in throw types that are not intended for this (be it int , char , etc.). Use special types-heirs of std::exception , created specifically for this purpose, or, if necessary, create your own type, inheriting from all the same std::exception . Of course, you can also write your own base type for exceptions, but that’s another story :) - Vlad Sivirin

1 answer 1

In addition to a couple of trivialities, the main thing is that you did not write a try block, but only a catch in the main function ...

 void Foo(int a) { try { if (a > 0) throw 1; else throw "Digit is negative!\n\n"; } catch (int) { cout << "Digit is positive!\n\n"; } } int main() { int a; cout << "Enter digit:"; cin >> a; try { Foo(a); } catch (const char * res) { cout << res << endl; } }