Clarification regarding C++ Exception Handling / Throwing
Consider the following code:
try {
int *i = NULL;
i[100] = 20;
catch (...) {
std::cout << "Exception Caught";
}
When running this code, it crashes (obviously, accessing a NULL pointer). Although, in Debug mode, Visual Studio states about an Uncaught exception, regarding write access violation.. also understandable.
I expected an exception to be caught here, but none is.
My concl开发者_运维问答usion is that no exception is being thrown. So why is VS alerting about an uncaught exception ?This question all started when I wanted to protect myself from code by another programmer, and wanted to wrap the calls to his functions with try-catch, assuming that he might be doing some access violations. But if I can only catch exceptions that are expicitily thrown, I'm pretty screwed. The only other explanation I may have is that this is because of some kind of Project or compiler configuration. I ran this in a new C++ Console Application is VS2005.
Thanks
In order for catch(...) to catch so-called structured exceptions you need to enable that in project settings.
Access violation is not C++ exception and cannot be caught by catch operator. Unhandled exception message in the Output window doesn't mean that this is C++ exception. First-chance and unhandled exception messages are generated both for C++ exceptions and any other exceptions like access violation. Non-C++ exceptions can be caught by __try - __except block.
The exception you are trying to catch is SEH exception. You may use __try, __except, __finally keywords
C++ doesn't specify array bounds checking and never has. The "error" in this instance is that the run-time system reports a segmentation fault as an Exception.
C++ exceptions only handle exceptions that are created by a "throw" statement. They are not related to machine exceptions (like accessing invalid memory). Windows however introduced n C++-exception-like scheme to handle machine errors, called "Structured Exception Handling". Unfortunately, it doesn't match very well with C++ because the stack unwinding process does not call the lingering destructors.
So they've added a way to map machine exceptions to C++ exception: You can provide a callback function which is called when a machine exception occurs and you can throw a C++ exception from that callback (unlike a signal handler) and that exception is used to unwind the stack, this time in the C++ way. _set_se_translator() sets this callback and here is the corresponding page in the MSDN:
http://msdn.microsoft.com/en-us/library/5z4bw5h5(VS.80).aspx
There is no C++ exception thrown when you dereference a null pointer, unlike in Java.
精彩评论