In C++, is there a standard way (or any other way, for that matter) to catch an exception triggered by a memory access violation?
For example, if something went wrong and the program tried to access something that it wasn't supposed to, how would you get an error message to appear saying "Memory Access Violation!" instead of just terminating the process and not showing the user any information about the crash?
I'm programming a game for Windows using MinGW, if that helps any.
Access violation
is a hardware exception and cannot be caught by a standard try...catch
.
Since the handling of hardware-exception are system specific, any solution to catch it inside the code would also be system specific.
On Unix/Linux you could use a SignalHandler
to do catch the SIGSEGV
signal.
On Windows you could catch these structured exception using the __try/__except
statement.
This doesn't quite help you, but access violations and other SEH exceptions can be caught in MSVC using try
...catch(...)
, if you compile with /EHa
:
Live demo
#include <iostream>
int main() {
try {
*(int*)0 = 0;
}
catch (...) {
std::cerr << "Exception!\n";
}
}
Output:
Exception!
The only downside is you have no way of knowing what went wrong. To know more about the exception you can set a custom SEH translator function with _set_se_translator like in this article.
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