Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Several classes for exception handling

0.00/5 (No votes)
19 Jan 2002 1  
C++ wrappers for stack trace, unhandled exception and win32 structured exceptions

Disclaimer

I am not MS certified developer and my opinion and code may have some bugs.
Use it carefully at your own risk.

Introduction

After familiarization with .NET Framework and System.Exception Object everyone can exclaim "Wow, it's really cool to be able to trace a call stack via a single call of Exception.StackTrace". But I write most of my working projects in VC++ 6.0. and I want to have a similar feature there too. Fortunately I can easily implement an "exception with stack trace" in C++. I recommend strongly to read the book "Debugging application" by John Robbins to get a better understanding about the subject. You can find here some ideas\code from John Robbins's book throughout my code. Also you can read the source code of my demo program and at last read this article too.

Main

Every programmer sometimes errs and tries to work with a wrong pointer. And it's real headache to detect the line of code with the bug. Look at this example of code with just such an annoying "access violation" error

try
{        
    char * p = 0;        
    printf("%u", strlen(p)); // oops

}
catch(se_translator::access_violation& ex)
{
    sym_engine::stack_trace(os, ex.info()->ContextRecord);        
}

But now have a look at this screenshot from VC IDE output window.

First-chance exception in Exception.exe: 0xC0000005: Access Violation.
First-chance exception in Exception.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception.
intel\strlen.asm(78) : Exception.exe at strlen()
D:\Exception\Exception.cpp(185) : Exception.exe at foo()
D:\Exception\Exception.cpp(65) : Exception.exe at main()
crt0.c(206) : Exception.exe at mainCRTStartup()
 (0) : KERNEL32.dll at GlobalGetAtomNameA()

vc ide

Just double click and it point you to a bug's code directly. It's magic, isn't it ?

Ok, Let's be deep in a subject and familiarize with source code. There are two main parts of magic:

  1. sym_enigne class
  2. se_translator class

The sym_engine class incapsulates Symbol Handler and Debugging Service API. With the aid of StackWalk API we can obtain a stack trace without problem. Especially it very easy in SEH frame. Have a look on the code below.

int exception_filter(std::ostream& os, EXCEPTION_POINTERS * pex)
{
    sym_engine::stack_trace(os, pex->ContextRecord);
    return EXCEPTION_EXECUTE_HANDLER ;
}
void foo (std::ostream& os)
{        
    __try {
        // any buggy code here

    }
    __except(exception_filter(os, GetExceptionInformation())) {
    }
}

For obtaining a stack trace we need a CONTEXT structure. And we can get it via call GetExceptionInformation() in the filter expression of an SEH exception handler. Ok. But we can't get such info in C++ catch(...) block. So, then we have to call the se_translator class for help.

The se_translator class maps win32 structured exceptions into C++ typed exceptions via _set_se_translator API. The CP site already has article SEH and C++ Exceptions - catch all in one by Martin Ziacek about using _set_se_translator and I don't want to repeat it. Instead I rewrite foo() function in C++ style.

se_translator translator;        // install a new translator function

void foo(std::ostream& os)
{    
    try
    {    
        // force to install a exception frame

        WORKAROUND_VCPP_SYNCHRONOUS_EXCEPTION
        char * p = 0;
        printf("%u", strlen(p));    // oops

    }
    catch(se_translator::access_violation& ex)
    {
        sym_engine::stack_trace(os, ex.info()->ContextRecord);        
    }
}

At first, I've installed a new translator function and now I can handle structured exception like C++ exception. I've wrapped every structured exception into C++ class. The base class is se_translator::exception. And for example several derived classes : se_translator::no_memory, se_translator::access_violation, se_translator::int_divide_by_zero, etc.

Yes, now we've grasped the way to obtaining stack for Win32 structured exception. But interesting, is there any way for obtaining similar info for native C++ exception like std::exception and so on ? Hm, I can't achieve it, but can propose a workaround. We can define the new exception class derived from std::exception which will hold the class stack's info. Let's name it exception2 class.

    try
    {        
        throw exception2("my exception");    // stores the stack info here

    }
    catch(exception2& ex)
    {
        os << ex.what() << std::endl;
        os << ex.stack_trace() << std::endl;
    }

At last the final class which I want to present it's exception_trap class. What if exception will be raised out from any exception frame ? Most likely the users will phone and terrorize your QA and you will tear hair at a loss. But if you could have a look at the crash's call stack definitely your life would become more easy. The exception_trap class wrapps SetUnhandledExceptionFilter API and can print out the crash's cause, call stack and another useful info. For this you must just define somewhere global variable.

    exception_trap<> trap;
Enjoy :)

Some traps

As any programmer knows, any good idea always has a some traps. In that case it's in synchronous exception model (/EHs compiler option) and _set_se_translator API. Sometimes due to optimization reasons the compiler can avoid to generate code for try\catch block. See MSDN article for more info. Hence if access violation or another exceptions will be occured nobody can catch it and tricks with SE translator will useless here.

I know two ways for avoiding such ugly scenario.

  • use asynchronous exception handling model (/EHa compiler option)
  • manually force the compiler to generate code for try\catch block, for example via using my macro WORKAROUND_VCPP_SYNCHRONOUS_EXCEPTION.

I can't name it the best solution but it's working.

Project's settings

Make sure what you set a next options:

  • compiler option: /GX (Enable Exception Handling)

If you want to use the symbol engine in your release version too

  • compiler option: /Zi (Produces a program database (.PDB file) )
  • linker option: /DEBUG (Generate Debug Info)

and don't forget to place the .pdb file in the same folder with your .exe or .dll file (see MSDN topic SymInitialize for more info)
And again I point to the book "Debugging application" by John Robbins for more info about program database problem.

Thanks

Sven Axelsson for "Using an output stream for debugging"
Rostislav Sharafutdinov for some correction

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here