Catching access violation exceptions? - c++

Example
int *ptr;
*ptr = 1000;
can I catch memory access violation exception using standard C++ without using any microsoft specific.

Read it and weep!
I figured it out. If you don't throw from the handler, the handler will just continue and so will the exception.
The magic happens when you throw you own exception and handle that.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>
void SignalHandler(int signal)
{
printf("Signal %d",signal);
throw "!Access Violation!";
}
int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGSEGV , SignalHandler);
try{
*(int *) 0 = 0;// Baaaaaaad thing that should never be caught. You should write good code in the first place.
}
catch(char *e)
{
printf("Exception Caught: %s\n",e);
}
printf("Now we continue, unhindered, like the abomination never happened. (I am an EVIL genius)\n");
printf("But please kids, DONT TRY THIS AT HOME ;)\n");
}

There is a very easy way to catch any kind of exception (division by zero, access violation, etc.) in Visual Studio using try -> catch (...) block. A minor project settings tweaking is enough. Just enable /EHa option in the project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!
See details here:
https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-160

Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.

At least for me, the signal(SIGSEGV ...) approach mentioned in another answer did not work on Win32 with Visual C++ 2015. What did work for me was to use _set_se_translator() found in eh.h. It works like this:
Step 1) Make sure you enable Yes with SEH Exceptions (/EHa) in Project Properties / C++ / Code Generation / Enable C++ Exceptions, as mentioned in the answer by Volodymyr Frytskyy.
Step 2) Call _set_se_translator(), passing in a function pointer (or lambda) for the new exception translator. It is called a translator because it basically just takes the low-level exception and re-throws it as something easier to catch, such as std::exception:
#include <string>
#include <eh.h>
// Be sure to enable "Yes with SEH Exceptions (/EHa)" in C++ / Code Generation;
_set_se_translator([](unsigned int u, EXCEPTION_POINTERS *pExp) {
std::string error = "SE Exception: ";
switch (u) {
case 0xC0000005:
error += "Access Violation";
break;
default:
char result[11];
sprintf_s(result, 11, "0x%08X", u);
error += result;
};
throw std::exception(error.c_str());
});
Step 3) Catch the exception like you normally would:
try{
MakeAnException();
}
catch(std::exception ex){
HandleIt();
};

This type of situation is implementation dependent and consequently it will require a vendor specific mechanism in order to trap. With Microsoft this will involve SEH, and *nix will involve a signal
In general though catching an Access Violation exception is a very bad idea. There is almost no way to recover from an AV exception and attempting to do so will just lead to harder to find bugs in your program.

As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
http://www.codeproject.com/KB/cpp/exception.aspx

Not the exception handling mechanism,
But you can use the signal() mechanism that is provided by the C.
> man signal
11 SIGSEGV create core image segmentation violation
Writing to a NULL pointer is probably going to cause a SIGSEGV signal

A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

Related

handling SEH exception of specific type (access violation only)

In order to handle access violation exception, project should be configured with SEH Exceptions (/EHa).
I'm looking for handling access violation exceptions only. According to this Microsoft publication here, in order to catch this SEH exceptions, one must use the general catch catch(...) that will catch all exception.
The question is whether there's an option to handle this exception in specific and leave other SEH unhandled, not necessarily by using the try/catch pattern.
UPDATE: thanks to the link in a comment below, I've found out about the __try/__except structure to handle SEH exceptions with many intrinsic functions that may put some more details about the exception nature.
In may case, i only care about AV exception, and i wish to avoid it. However, I'm using C++ and prefer using the standard try/catch structure (while configuring The /EHa compiler option).
Is there an option to use those intrinsic function in order to check the exception type in my case ?
using _set_se_translator I can define the required behavior in SEH exception only, leaving all non-seh exception to the catch statement.
I defined the following handling (should be set per thread) :
void mySEHtranslator(unsigned int exceptionCode, PEXCEPTION_POINTERS exceptionRecord)
{
if (exceptionRecord->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
{
puts("access violation not count");
}
else
{
throw "1"; // does not suppose to be caught.
}
}
and in the relevant code section where i want to imply the translator that ignore access violation :
void mycode()
{
_set_seh_translator(mySEHtranslator);
try {
.... my code ...
}
catch (...) // does not suppose to catch the "1"
{
}
}
additional reference can be found here

Exception 0xC0000005 not being caught [duplicate]

Example
int *ptr;
*ptr = 1000;
can I catch memory access violation exception using standard C++ without using any microsoft specific.
Read it and weep!
I figured it out. If you don't throw from the handler, the handler will just continue and so will the exception.
The magic happens when you throw you own exception and handle that.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>
void SignalHandler(int signal)
{
printf("Signal %d",signal);
throw "!Access Violation!";
}
int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGSEGV , SignalHandler);
try{
*(int *) 0 = 0;// Baaaaaaad thing that should never be caught. You should write good code in the first place.
}
catch(char *e)
{
printf("Exception Caught: %s\n",e);
}
printf("Now we continue, unhindered, like the abomination never happened. (I am an EVIL genius)\n");
printf("But please kids, DONT TRY THIS AT HOME ;)\n");
}
There is a very easy way to catch any kind of exception (division by zero, access violation, etc.) in Visual Studio using try -> catch (...) block. A minor project settings tweaking is enough. Just enable /EHa option in the project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!
See details here:
https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-160
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
At least for me, the signal(SIGSEGV ...) approach mentioned in another answer did not work on Win32 with Visual C++ 2015. What did work for me was to use _set_se_translator() found in eh.h. It works like this:
Step 1) Make sure you enable Yes with SEH Exceptions (/EHa) in Project Properties / C++ / Code Generation / Enable C++ Exceptions, as mentioned in the answer by Volodymyr Frytskyy.
Step 2) Call _set_se_translator(), passing in a function pointer (or lambda) for the new exception translator. It is called a translator because it basically just takes the low-level exception and re-throws it as something easier to catch, such as std::exception:
#include <string>
#include <eh.h>
// Be sure to enable "Yes with SEH Exceptions (/EHa)" in C++ / Code Generation;
_set_se_translator([](unsigned int u, EXCEPTION_POINTERS *pExp) {
std::string error = "SE Exception: ";
switch (u) {
case 0xC0000005:
error += "Access Violation";
break;
default:
char result[11];
sprintf_s(result, 11, "0x%08X", u);
error += result;
};
throw std::exception(error.c_str());
});
Step 3) Catch the exception like you normally would:
try{
MakeAnException();
}
catch(std::exception ex){
HandleIt();
};
This type of situation is implementation dependent and consequently it will require a vendor specific mechanism in order to trap. With Microsoft this will involve SEH, and *nix will involve a signal
In general though catching an Access Violation exception is a very bad idea. There is almost no way to recover from an AV exception and attempting to do so will just lead to harder to find bugs in your program.
As stated, there is no non Microsoft / compiler vendor way to do this on the windows platform. However, it is obviously useful to catch these types of exceptions in the normal try { } catch (exception ex) { } way for error reporting and more a graceful exit of your app (as JaredPar says, the app is now probably in trouble). We use _se_translator_function in a simple class wrapper that allows us to catch the following exceptions in a a try handler:
DECLARE_EXCEPTION_CLASS(datatype_misalignment)
DECLARE_EXCEPTION_CLASS(breakpoint)
DECLARE_EXCEPTION_CLASS(single_step)
DECLARE_EXCEPTION_CLASS(array_bounds_exceeded)
DECLARE_EXCEPTION_CLASS(flt_denormal_operand)
DECLARE_EXCEPTION_CLASS(flt_divide_by_zero)
DECLARE_EXCEPTION_CLASS(flt_inexact_result)
DECLARE_EXCEPTION_CLASS(flt_invalid_operation)
DECLARE_EXCEPTION_CLASS(flt_overflow)
DECLARE_EXCEPTION_CLASS(flt_stack_check)
DECLARE_EXCEPTION_CLASS(flt_underflow)
DECLARE_EXCEPTION_CLASS(int_divide_by_zero)
DECLARE_EXCEPTION_CLASS(int_overflow)
DECLARE_EXCEPTION_CLASS(priv_instruction)
DECLARE_EXCEPTION_CLASS(in_page_error)
DECLARE_EXCEPTION_CLASS(illegal_instruction)
DECLARE_EXCEPTION_CLASS(noncontinuable_exception)
DECLARE_EXCEPTION_CLASS(stack_overflow)
DECLARE_EXCEPTION_CLASS(invalid_disposition)
DECLARE_EXCEPTION_CLASS(guard_page)
DECLARE_EXCEPTION_CLASS(invalid_handle)
DECLARE_EXCEPTION_CLASS(microsoft_cpp)
The original class came from this very useful article:
http://www.codeproject.com/KB/cpp/exception.aspx
Not the exception handling mechanism,
But you can use the signal() mechanism that is provided by the C.
> man signal
11 SIGSEGV create core image segmentation violation
Writing to a NULL pointer is probably going to cause a SIGSEGV signal
A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

Recoverying from exceptions

In our application (c++) we load 3rd party DLLs using LoadLibrary.
Sometimes these DLLs cause exceptions, such as "Access violation reading location 0x00000000..".
Is it possible to recover from such an exception, for example using try & catch or some other mechanism? in other world, is that possible to create a sandbox within the same process that withstand such events?
Thank you
No. It's not. A DLL has unrestricted access to the process context that calls it. You need to run untrustable DLLs in their own process context.
In Windows, with VisualStudio compiler, may use SEH mechanism.
__try
{
char* ptr = 0;
char val = *ptr;
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
{
std::cout<<"AV"<<std::endl;
}
Use option /EHa.
You could try a different type of exception handler:
__try
{
// Code that might cause an access violation goes here.
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
int code = _exception_code();
}
Beware though, such handlers can't be used in any routine where C++ objects need stack unwinding as the compiler will warn you (irritatingly).
You can try the /EH flag - http://msdn.microsoft.com/en-us/library/1deeycx5%28v=vs.80%29.aspx - in Visual Studio, but access violation exceptions most likely mean you're doing something very wrong. I'd let the program crash and try to solve the exception, rather than catching it.
It is not possible in c++ if, it is not possible throws a crossmodules exceptions anymore in any case you will have a memory corruption in your application so you have to find out what is going wrong in your dll. You can check the reason you cant throw exception from dll here:
http://www.codeproject.com/Articles/28969/HowTo-Export-C-classes-from-a-DLL
The people behind Runtime-Compiled C++ are using a thing called Structured Exception Handling for their DLL crash-handling routines. Dig into their website or ask them if you want some code samples.
According to the MSDN, the /EHa switch enables "C++ exception handling with structured exception handling exceptions". So if you're using the msvc compiler, you might want to try this.

How to catch divide-by-zero error in Visual Studio 2008 C++?

How can I catch a divide-by-zero error (and not other errors; and to be able to access exception information) in Visual Studio 2008 C++?
I tried this:
try {
int j=0;
int i= 1/j;//actually, we call a DLL here, which has divide-by-zero
} catch(std::exception& e){
printf("%s %s\n", e.what());
} catch(...){
printf("generic exception");
}
But this goes to the generic ... catch block. I understand that the MS-specific __try may be useful here, but I'd prefer standard C++, and in any case I have destructors which prevent the use of __try.
CLARIFICATION: The code above is simplified for discussion purposes. Actually, the divide-by-zero is a bug which occurs deep in a third-party DLL for which I do not have the source code. The error depends on the parameter (a handle to a complex structure) which I pass to the library, but not in any obvious way. So, I want to be able to recover gracefully.
Assuming that you can't simply fix the cause of the exception generating code (perhaps because you don't have the source code to that particular library and perhaps because you can't adjust the input params before they cause a problem).
You have to jump through some hoops to make this work as you'd like but it can be done.
First you need to install a Structured Exception Handling translation function by calling _set_se_translator() (see here) then you can examine the code that you're passed when an SEH exception occurs and throw an appropriate C++ exception.
void CSEHException::Translator::trans_func(
unsigned int code,
EXCEPTION_POINTERS *pPointers)
{
switch (code)
{
case FLT_DIVIDE_BY_ZERO :
throw CMyFunkyDivideByZeroException(code, pPointers);
break;
}
// general C++ SEH exception for things we don't need to handle separately....
throw CSEHException(code, pPointers);
}
Then you can simply catch your CMyFunkyDivideByZeroException() in C++ in the normal way.
Note that you need to install your exception translation function on every thread that you want exceptions translated.
C++ does not handle divide-by-zero as an exception, per-se.
Quoting Stroustrup:
"low-level events, such as arithmetic
overflows and divide by zero, are
assumed to be handled by a dedicated
lower-level mechanism rather than by
exceptions. This enables C++ to match
the behaviour of other languages when
it comes to arithmetic. It also avoids
the problems that occur on heavily
pipelined architectures where events
such as divide by zero are
asynchronous."
"The Design and Evolution of C++" (Addison Wesley, 1994)
In any case, exceptions are never a replacement for proper precondition handling.
To catch divide by zero exceptions in Visual C++ try->catch (...) just enable /EHa option in project settings. See Project Properties -> C/C++ -> Code Generation -> Modify the Enable C++ Exceptions to "Yes With SEH Exceptions". That's it!
See details here:
http://msdn.microsoft.com/en-us/library/1deeycx5(v=vs.80).aspx
You can either use structured exception handling (using __try etc.) or you can install a structured exception handler translator: _set_se_translator
Both of these are operating system specific.
You can not do that using standard C++ as it is not standard C++ exception. It's a structured exception. For the standard C++ exception somebody has to do a throw exception; from the code.
Why not check for this before? The performance will be trivial for a simple j == 0 compared to context-switching for exception handling.
A good approach would be to use safe object oriented wrappers like SafeInt. It also seems to be integrated in Visual Studio 2010.
update:
If the division-by-zero happens in third party code your only option is SEH or something equivalent as answered by Seb Rose
Try the following code:
try
{
const int j=0;
if (j == 0) { throw std::exception("j was 0"); }
const int i= 1/j;
}
catch(std::exception& e)
{
printf("%s %s\n", e.what());
}
catch(...)
{
printf("generic exception");
}
Of course, if you're OK doing this without exceptions, you could do:
const int j = 0;
if (j == 0)
{
/* do something about the bad pre-condition here */
}
else
{
const int i = 1 / j;
}
Edit in response to clarification: you'll have to figure out what input it is that you're handing the third party that causes them to divide by zero before-hand, and handle that before ever calling their function.
You can use try-except Statement.
But, don't forget that you need to set it for each thread.

C++ catching all exceptions

Is there a c++ equivalent of Java's
try {
...
}
catch (Throwable t) {
...
}
I am trying to debug Java/jni code that calls native windows functions and the virtual machine keeps crashing. The native code appears fine in unit testing and only seems to crash when called through jni. A generic exception catching mechanism would prove extremely useful.
try{
// ...
} catch (...) {
// ...
}
will catch all C++ exceptions, but it should be considered bad design. You can use c++11's new current_exception mechanism, but if you don't have the ability to use c++11 (legacy code systems requiring a rewrite), then you have no named exception pointer to use to get a message or name. You may want to add separate catch clauses for the various exceptions you can catch, and only catch everything at the bottom to record an unexpected exception. E.g.:
try{
// ...
} catch (const std::exception& ex) {
// ...
} catch (const std::string& ex) {
// ...
} catch (...) {
// ...
}
Someone should add that one cannot catch "crashes" in C++ code. Those don't throw exceptions, but do anything they like. When you see a program crashing because of say a null-pointer dereference, it's doing undefined behavior. There is no std::null_pointer_exception. Trying to catch exceptions won't help there.
Just for the case someone is reading this thread and thinks he can get the cause of the program crashes. A Debugger like gdb should be used instead.
This is how you can reverse-engineer the exception type from within catch(...) should you need to (may be useful when catching unknown from a third party library) with GCC:
#include <iostream>
#include <exception>
#include <typeinfo>
#include <stdexcept>
int main()
{
try {
throw ...; // throw something
}
catch(...)
{
std::exception_ptr p = std::current_exception();
std::clog <<(p ? p.__cxa_exception_type()->name() : "null") << std::endl;
}
return 1;
}
and if you can afford using Boost you can make your catch section even simpler (on the outside) and potentially cross-platform
catch (...)
{
std::clog << boost::current_exception_diagnostic_information() << std::endl;
}
try {
// ...
} catch (...) {
// ...
}
Note that the ... inside the catch is a real ellipsis, ie. three dots.
However, because C++ exceptions are not necessarily subclasses of a base Exception class, there isn't any way to actually see the exception variable that is thrown when using this construct.
it is not possible (in C++) to catch all exceptions in a portable manner. This is because some exceptions are not exceptions in a C++ context. This includes things like division by zero errors and others. It is possible to hack about and thus get the ability to throw exceptions when these errors happen, but it's not easy to do and certainly not easy to get right in a portable manner.
If you want to catch all STL exceptions, you can do
try { ... } catch( const std::exception &e) { ... }
Which will allow you do use e.what(), which will return a const char*, which can tell you more about the exception itself. This is the construct that resembles the Java construct, you asked about, the most.
This will not help you if someone is stupid enough to throw an exception that does not inherit from std::exception.
In short, use catch(...). However, note that catch(...) is meant to be used in conjunction with throw; basically:
try{
foo = new Foo;
bar = new Bar;
}
catch(...) // will catch all possible errors thrown.
{
delete foo;
delete bar;
throw; // throw the same error again to be handled somewhere else
}
This is the proper way to use catch(...).
it is possible to do this by writing:
try
{
//.......
}
catch(...) // <<- catch all
{
//.......
}
But there is a very not noticeable risk here: you can not find the exact type of error that has been thrown in the try block, so use this kind of catch when you are sure that no matter what the type of exception is, the program must persist in the way defined in the catch block.
You can use
catch(...)
but that is very dangerous. In his book Debugging Windows, John Robbins tells a war story about a really nasty bug that was masked by a catch(...) command. You're much better off catching specific exceptions. Catch whatever you think your try block might reasonably throw, but let the code throw an exception higher up if something really unexpected happens.
Let me just mention this here: the Java
try
{
...
}
catch (Exception e)
{
...
}
may NOT catch all exceptions! I've actually had this sort of thing happen before, and it's insantiy-provoking; Exception derives from Throwable. So literally, to catch everything, you DON'T want to catch Exceptions; you want to catch Throwable.
I know it sounds nitpicky, but when you've spent several days trying to figure out where the "uncaught exception" came from in code that was surrounded by a try ... catch (Exception e)" block comes from, it sticks with you.
Well, if you would like to catch all exception to create a minidump for example...
Somebody did the work on Windows.
See http://www.codeproject.com/Articles/207464/Exception-Handling-in-Visual-Cplusplus
In the article, he explains how he found out how to catch all kind of exceptions and he provides code that works.
Here is the list you can catch:
SEH exception
terminate
unexpected
pure virtual method call
invalid parameter
new operator fault
SIGABR
SIGFPE
SIGILL
SIGINT
SIGSEGV
SIGTERM
Raised exception
C++ typed exception
And the usage:
CCrashHandler ch;
ch.SetProcessExceptionHandlers(); // do this for one thread
ch.SetThreadExceptionHandlers(); // for each thred
By default, this creates a minidump in the current directory (crashdump.dmp)
Be aware
try{
// ...
} catch (...) {
// ...
}
catches only language-level exceptions, other low-level exceptions/errors like Access Violation and Segmentation Fault wont be caught.
A generic exception catching mechanism
would prove extremely useful.
Doubtful. You already know your code is broken, because it's crashing. Eating exceptions may mask this, but that'll probably just result in even nastier, more subtle bugs.
What you really want is a debugger...
Can you run your JNI-using Java application from a console window (launch it from a java command line) to see if there is any report of what may have been detected before the JVM was crashed. When running directly as a Java window application, you may be missing messages that would appear if you ran from a console window instead.
Secondly, can you stub your JNI DLL implementation to show that methods in your DLL are being entered from JNI, you are returning properly, etc?
Just in case the problem is with an incorrect use of one of the JNI-interface methods from the C++ code, have you verified that some simple JNI examples compile and work with your setup? I'm thinking in particular of using the JNI-interface methods for converting parameters to native C++ formats and turning function results into Java types. It is useful to stub those to make sure that the data conversions are working and you are not going haywire in the COM-like calls into the JNI interface.
There are other things to check, but it is hard to suggest any without knowing more about what your native Java methods are and what the JNI implementation of them is trying to do. It is not clear that catching an exception from the C++ code level is related to your problem. (You can use the JNI interface to rethrow the exception as a Java one, but it is not clear from what you provide that this is going to help.)
For the real problem about being unable to properly debug a program that uses JNI (or the bug does not appear when running it under a debugger):
In this case it often helps to add Java wrappers around your JNI calls (i.e. all native methods are private and your public methods in the class call them) that do some basic sanity checking (check that all "objects" are freed and "objects" are not used after freeing) or synchronization (just synchronize all methods from one DLL to a single object instance). Let the java wrapper methods log the mistake and throw an exception.
This will often help to find the real error (which surprisingly is mostly in the Java code that does not obey the semantics of the called functions causing some nasty double-frees or similar) more easily than trying to debug a massively parallel Java program in a native debugger...
If you know the cause, keep the code in your wrapper methods that avoids it. Better have your wrapper methods throw exceptions than your JNI code crash the VM...
If you are looking for Windows-specific solution then there is structured exception handling:
https://learn.microsoft.com/en-us/cpp/cpp/try-except-statement
The code looks as follows
__try
{
// code here may throw or make access violation
}
__except( EXCEPTION_EXECUTE_HANDLER )
{
// after exception code here, e.g. log the error
}
It will catch not only C++ exceptions but also access violations or other system exceptions.
Well this really depends on the compiler environment.
gcc does not catch these.
Visual Studio and the last Borland that I used did.
So the conclusion about crashes is that it depends on the quality of your development environment.
The C++
specification says that catch(...) must catch any exceptions, but it doesn't in all cases.
At least from what I tried.