C++ Exceptions

P

praviarun

I found that the following code catches exception on gcc 4.0
i.e it prints "caught standard exception"


try{
vector<int> test;
test.at(0); // this line throws an exception

}
catch(...)
{
printf("caught standard exception");

}

but the following code which dereferences a null pointer does not throw
an exception

try{
int *p = 0;
*p =10;

}
catch(...)
{

printf("caught dereferencing null pointer");

}

This code simply terminates without catching an exception
I am using Xcode

Please let me know how i could catch this exception


Praveen
 
D

Dizzy

but the following code which dereferences a null pointer does not throw
an exception

try{
int *p = 0;
*p =10;

}
catch(...)
{

printf("caught dereferencing null pointer");

}

Of course it does not.
This code simply terminates without catching an exception
I am using Xcode

Where does in the C++ standard text says that dereferencinging an invalid
pointer (null included) should throw a C++ exception ?
Please let me know how i could catch this exception

There is no C++ exception thrown, thus there is no C++ exception to catch.
If you do not want to have such an issue make sure you do not dereference
invalid pointers (using references helps with that by requiring to be
initilized although of course you may still have object lifetime issues).

You seem to confuse "exceptions" as a general term/concept with C++
exceptions language feature. They are not the same. What you do there is
just to invoke "undefined behaivour". Your thread is very similar to one
discussed here recently about exceptions (not) thrown on division by 0.
 
M

mlimber

Pete said:
In standard C++, if you don't throw it, you can't catch it. Hardware
"exceptions" are not the same thing as C++ "exceptions".

Right. In non-standard C++, exceptions of a sort can sometimes thrown
for errors of this kind (cf. Microsoft's "structured exceptions"), but
for more on that, the OP will need to ask on a forum that deals with
his specific compiler or platform.

Cheers! --M
 
G

Grizlyk

This code simply terminates without catching an exception

Please let me know how i could catch this exception

Can not, but you can try use signal handlers (see signal.h), if your
system generates and allows to catch signals in the case. I am not
shure you will can continue execution after the error, but will can
print error message.
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top