Recoverying from exceptions

1.3k views Asked by At

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

6

There are 6 answers

14
JTeagle On BEST ANSWER

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).

0
David Schwartz On

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.

2
Luchian Grigore On

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.

0
AlexTheo On

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

3
fat_lor_troll On

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.

0
Laurent Couvidou On

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.