Help with this C++ snippet

Could anyone tell me why this program is crashing under gcc 4.4.5? Aborts with the following error messge:

terminate called after throwing an instance of 'std::string'


Thanks in advance.



---------------------------------------------------


#include <iostream>
#include <memory>

using namespace std;


auto_ptr<int> f() throw()
{
auto_ptr<int> p (new int);
*p = 1234;

throw string("This is an error");

return p;
}

int main(int argc, char **argv)
{
auto_ptr<int> p = f();

return 0;
}
Last edited on
It does exactly what you told it to do:
throw string("This is an error");

If you don't catch it it's the end my friend...

Throw makes absolutely no sense there.

Last edited on
Thanks very much for the quick reply. Sorry for posting an incomplete test program that is still crashing with the following error message:

terminate called after throwing an instance of 'std::string'
Aborted


---------------------------------------------



#include <iostream>
#include <memory>

using namespace std;


auto_ptr<int> f() throw()
{
auto_ptr<int> p (new int);
*p = 1234;

// int* f = p.release();
// delete f;

throw string("This is an error");
*p = 5678;

return p;
}

int main(int argc, char **argv)
{
try {
auto_ptr<int> p = f();
}
catch (...)
{
}

return 0;
}
@community

Doesen't
auto_ptr<int> f() throw()
mean that f() does not throw at all?

*scratching my head*
You are right, sorry!
closed account (zb0S216C)
Caligulaminus wrote:
Doesen't
auto_ptr<int> f() throw()
mean that f() does not throw at all?

Yes.

When you throw an exception, you're expected to catch it, otherwise your program terminates prematurely. In order to catch an exception, you need to try before you can catch it. For example:

1
2
3
4
5
6
7
8
9
try
{
    // ...
}

catch( /* Exception */ )
{
    // Handle exception...
}

Once an exception is thrown within a method, the methods stops; meaning that remaining statements within the method are never executed. This is the same for a try block. When an exception is thrown within a try block, the remaining statements are never executed, and the control is passed to the catch block that handles the thrown exception.

Wazzak
Last edited on
closed account (S6k9GNh0)
http://cplusplus.com/doc/tutorial/exceptions/
closed account (1yR4jE8b)
Doesen't
auto_ptr<int> f() throw()
mean that f() does not throw at all?


This is only a hint for the programmer, and *absolutely nothing is guaranteed by the compiler*. There are some minor optimizations that the Visual C++ compiler makes for non-throwing functions with the empty throw() clause but they hardly mean anything.

I reiterate: do not depend on these throws declarations, you are not guaranteed anything by the compiler and it is only a hint for someone reading the code.

(I barely ever use them, they're mostly pointless)
Topic archived. No new replies allowed.