exception throwing

In the tutorial for exception, section "Exception specifications". It says

1
2
int myfunction (int param) throw(); // no exceptions allowed
int myfunction (int param);         // all exceptions allowed 


I have tried throw() and explicitly throw an exception of int in a function.

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
#include <iostream>

using namespace std;

int getInt(int i) throw(int) {
	throw 1;
	return i;
}

int main() {
	try {
		try {
			cout << getInt(10) << " " << getInt(20) << endl;
		}
		catch(int f) {
			cout << "int: " << f << endl;
			throw;
		}
		catch(...) {
			cout << "default" << endl;
			throw;
		}
	}
	catch(int i) {
		cout << "outer int: " << i << endl;
	}
	catch(...) {
		cout << "outer default" << endl;
	}

	return 0;
}


However, the throw is still successful and is caught by the inner catch on int. Is there something I have done wrong to the tutorial that the int is caught by the inner catch statement?
int getInt(int i) throw(int)
means that getInt could throw an int
I have tried throw() but the result is the same. BTW, I am using Visual C++ 2005. Is it the culprit?
learner2009 said:
I have tried throw() but the result is the same. BTW, I am using Visual C++ 2005. Is it the culprit?

Quite possibly.
MSVC takes departs frpm the official exception specification .
1
2
3
4
5
int getInt(int i) throw(int) {
	throw 1;
	return i;
}


I quote from the MSVC help:
Function exception specifiers other than throw() are parsed but not used. For example:
void f() throw(int); // parsed but not used
void g() throw(); // parsed and used


Just FYI, exception specifications are stupid and there is little point to using them.

EDIT: Actually, the real problem is this:

Suppose you wrote a problem in which function A calls B which calls C which calls D. D can throw a Foo. So you write the exception specification for all four functions as "throw( Foo )".

Now you modify the program such that D now instantiates a vector, whose constructor could throw std::bad_alloc. Now you have to update the signatures of A, B, C, and D to include std::bad_alloc in the exception specification.

Now translate that into a project with hundreds or thousands of functions, and now you end up having to update potentially hundreds or thousands of functions. If that's even possible; before you can do that you have to figure out which functions can call which other functions which can call other functions that throw.... It is simply impractical. Solution: the benefits of using exception specifications are FAR outweighed by the maintenance cost. Don't use them.


Last edited on
Topic archived. No new replies allowed.