Stop after catch in C++
Jul 13, 2021 at 7:24am UTC
Hello,
After catch show function from t4 executed. I'd like to stop the program after the catch.
I'd like to create just three objects from the test class.
output is:
1
2
3
More than 3...3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#include <iostream>
using namespace std;
class test
{
public :
static int count;
test()
{
try {
if (count >= 3)
{
throw 505;
}
else
{
count++;
}
}
catch (...)
{
cout << "More than 3..." ;
}
}
void show()
{
cout << count << endl;
}
};
int test::count = 0;
int main()
{
test t1;
t1.show();
test t2;
t2.show();
test t3;
t3.show();
test t4;
t4.show();
return 0;
}
Last edited on Jul 13, 2021 at 7:26am UTC
Jul 13, 2021 at 8:16am UTC
For an abrupt end to your program:
exit( 0 );
Strictly, you will need
Please clarify what you want to happen if that is not it.
Last edited on Jul 13, 2021 at 8:17am UTC
Jul 13, 2021 at 8:52am UTC
Throwing and catching an exception in the same function makes little sense. The purpose of exceptions is to report problems that can't be handled in place.
Consider sth. like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <iostream>
class test
{
public :
static int count;
test()
{
if (count >= 3)
{
throw 505;
}
else
{
count++;
}
}
void show()
{
std::cout << count << "\n" ;
}
};
int test::count = 0;
int main()
{
try
{
test t1;
t1.show();
test t2;
t2.show();
test t3;
t3.show();
test t4;
t4.show();
}
catch (...)
{
std::cerr << "Exception caught.\n" ;
}
}
Jul 13, 2021 at 9:02am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
#include <iostream>
#include <cstdlib>
class test {
public :
inline static int count {};
test() {
if (count >= 3)
throw 505;
else
++count;
}
void show() {
std::cout << count << '\n' ;
}
};
int main()
{
try {
test t1;
t1.show();
test t2;
t2.show();
test t3;
t3.show();
test t4;
t4.show();
}
catch (int e) {
exit(((std::cout << "Error " << e << ". More than 3...\n" ), 1));
}
catch (...) {
exit(((std::cout << "Unknown exception\n" ), 2));
}
}
1
2
3
Error 505. More than 3...
Last edited on Jul 13, 2021 at 9:42am UTC
Jul 13, 2021 at 9:17am UTC
The use of exit()
here isn't the best as that's an unexpected side-effect of constructing test
, handling the exception in main()
is a better approach.
Topic archived. No new replies allowed.