In my c++ code, I have a block of code that gives me an "Access Violation Writing Location ..." Exception when user input is invalid..
I tried to catch this exception in my try/catch block to display error message when the exception occurs.. but for some reason it is not catching the error.
try {
// ... some code that causes Access Violation Writing Location Exception
}
catch (...) {
std::cout << "invalid user input" << endl;
}
I did this, but when the exception occurs, the console does not display my error message, but says there is an
Unhandled exception at 0x0F0B0E9A (msvcr110d.dll) in Example.exe : Access violation writing location
So it seems like my try/catch block is not catching the exception...
I set break points to make sure that the exception is occuring within the try block.. and I'm 100% that's the case..
Why is "catch (...)" not catching the Access Violation exception?
Don't do this!
An access violation is not a C++ exception. It is the operating system trying to terminate the application because it did something invalid.
Specifically, it tried to write to a memory address it did not have the privileges to access. This basically means you're writing to random memory, which means that even if you did catch this error and showed a nice error message to the user, it might not always work. Sometimes, instead of writing to memory that you don't have write permissions for, the program might end up writing over other parts of your program. That won't raise an access violation, so the problem won't be detected. It will just corrupt your program.
The only correct way to do this is to validate your user input. You have to check that the user input is in a form that your program can handle safely. If it isn't, you have to either correct it, or abort, and show an error to the user. You have to do that in your own code, before your application does something so bad that the OS is forced to try to terminate it.
Yes, there is a way to handle Access Violations, but as I said above, that is not the correct solution to your problem, so I see no reason to elaborate on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With