How to exit program immediately if an exception occurs (without executing the rest of the statements)

1
2
3
4
5
6
7
8
9
10
11
12
13

try
{
	cin >> foo;
}
catch ( exception& e )
{
	cerr << "Exception occured." << e.what() << endl;
	return(0);
}

cout << "Should not output this";



I receive the "Should not output this" output even when exception occurs in the cin >> foo statement.
Why doesn't return(0) work as I'm assuming it to work and what's the right way of doing it?

insert
 
exit(1);

inside your
 
catch

If line 4 throws an exception line 12 should never run. Are you sure it throws an exception?
Last edited on
Peter87 is right, it looks like an exception isn't ever being thrown.

For debugging purposes, try adding in a

cout << foo;

right after you try to read foo in. This will let you know if an error is occurring or if your program is reading in something that you aren't expecting/don't want it to.

In what context are you putting cin in a try block, by the way? That might help us figure out a better way to set this up.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// exceptions
#include <iostream>
using namespace std;
int foo=0;

int main () 
{
try
{
	cout << ":";
	cin >> foo;
	cout << foo << endl;
	throw 2;
}
catch (int e)
{
	cerr << "Exception occured." << e << endl;
	return(0);
}

cout << "Should not output this";
}


Reference : http://www.cplusplus.com/doc/tutorial/exceptions/
Last edited on
@ghantauke
If you were meaning to catch exeptions thrown by cin >> foo, you need to enable them first, try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main ()
{
    cin.exceptions(ios::failbit);
    int foo;
    try
    {
        cin >> foo;
    }
    catch (const exception& e)
    {
        cerr << "Exception occured." << e.what() << '\n';
        return 0;
    }
    cout << "An integer was successfully parsed\n";
}  
demo: http://ideone.com/DlYomT
Topic archived. No new replies allowed.