Why does C++ need throw()
I understand that An exception specification with an empty throw, as in
void MyFunction(int i) throw();
tells the compiler that the function does not throw any exceptions. But why do we need this function? If MyFunction doesn't want to throw() something, then just doesn't throw it.
What happens when MyFunction() throw() actually throws an exception?
[388 byte] By [
warrener] at [2007-11-20 11:58:34]

# 1 Re: Why does C++ need throw()
What happens when MyFunction() throw() actually throws an exception?Well, then your automatic/local variables won't be properly destructed and you'll end up with memory leaks and an unstable application.
// compile with: /EHs
#include "stdafx.h"
#include <stdio.h>
class myclass
{
public:
myclass()
{
printf_s("in ctor\n");
}
~myclass()
{
printf_s("in dtor\n");
}
};
void f1(void) throw(...)
{
myclass a;
throw 1;
}
void f2() throw()
{
myclass a;
throw 1;
}
int main()
{
try
{
f1(); // will clean up after itself
// f2(); // will omit myclass' destructor
} catch (...)
{
printf_s("in catch\n");
}
}
- petter
# 2 Re: Why does C++ need throw()
Thank you, wildfrog. You said exact what I want to say.
Then my question is why do people want to put a "throw()" here. Because of throw() myclass obj cannot clean itself!
Why bother introduce "throw()" ?
# 3 Re: Why does C++ need throw()
Well the default VC++ 2005 behaviour with synchronous exception handling is throw(...) and that results in more code and less performance. With throw() or __declspec(nothrow) you can reduce that overhead.
- petter