try and throw question

L

lixiaoyao

when I run the following code,it just generate "aborted",but the
anticipated answer is
"Caught \"char *\" exception" ,it seems to be no run the 'catch'
sentence.
please help!
#include <iostream>
using namespace std;
class CanThrowException
{
int *array;
public:
CanThrowException(int array_size) throw (char *) {
// if ((array = (int *)malloc(sizeof(int) * array_size)) == 0)
/* If allocation fails */
throw "Memory allocation failed";
}

//... Other stuff

};

int
main()
{
CanThrowException *ins;

try { /* Try to construct object */

ins = new CanThrowException(10);
}

catch (char *) { /* Catch any exception thrown by constructor */
cerr << "Caught \"char *\" exception" << endl;

}
// catch (...) { /* If constructor can throw anything else */
// cerr << "Caught unknown exception" << endl;
// }

}
 
A

Alf P. Steinbach

* lixiaoyao:
when I run the following code,it just generate "aborted",but the
anticipated answer is
"Caught \"char *\" exception" ,it seems to be no run the 'catch'
sentence.

The anticipation is incorrect.

please help!
#include <iostream>
using namespace std;
class CanThrowException
{
int *array;

Better use a std::vector said:
public:
CanThrowException(int array_size) throw (char *) {

Don't use throw specifications, except "throw()".. Although in this case it
captures a bug it leads to unmaintainable code. C++ isn't Java.

// if ((array = (int *)malloc(sizeof(int) * array_size)) == 0)
/* If allocation fails */
throw "Memory allocation failed";

Here you throw a "char const*".

That isn't what's specificed, so you end up with a call to std::terminate
(for a standard-conforming compiler).

Use standard exceptions such as std::runtime_error.

}

//... Other stuff

};

int
main()
{
CanThrowException *ins;

Don't use raw pointers.

Here: at least use a std::auto_ptr.

Better: don't use a pointer unless necessary, and it isn't here.
 
A

Alf P. Steinbach

* lixiaoyao:
// if ((array = (int *)malloc(sizeof(int) * array_size)) == 0)

Don't use 'malloc' (use C++ 'new' instead).

Don't use C-style casts.

Don't use raw pointers (here: use a std::vector<int> instead).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top