Forwarding Exceptions

How are you supposed to catch an exception and throw it again?
Currently the following exception is deleted after the first catch. When next catch comes the exception is deleted. Now if I throw a dynamically allocated exception it all works. However that is not standard. What is the standard way of catching and throwing the same exception?

Thanks.

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
51
52
53
54
//============================================================================
// Name        : exceptionTest.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Exception caught correctly the first time, but not forwarded correctly.  Why?
//============================================================================

#include <iostream>
#include <stdexcept>
using namespace std;

#include <string.h>
class NewException : public exception {
private:
	string message;
public:
	NewException(string message)throw(){
		cerr << "constructed" <<endl;
		this->message=message;
	}
	virtual ~NewException()throw(){
		cerr <<"deleted"<<endl;
	}
	virtual const char* what() const throw(){ return message.c_str(); }
};

void throwException()throw(exception){
	//throw NewException("this is a message");
	throw runtime_error("run time error");
}

void testException(int i){

try{
	if(i==5) 	throwException();
	else 		testException(i+1);
}catch(exception &e){
	cerr << e.what() <<endl;
	if(i!=1)throw e;
}
catch(...){
	cerr << "...caught"<<endl;
}
}

int main() {

	testException(1);


	return 0;
}
1
2
3
4
5
try {

} catch (...) {
throw; //rethrows the exception caught in ...
}
Also, I think you may need two nested try blocks.
ahh thanks :)
Topic archived. No new replies allowed.