views:

2735

answers:

6

Is there some way to catch exceptions which are otherwise unhandled (including those thrown outside the catch block)?

I'm not really concerned about all the normal cleanup stuff done with exceptions, just that I can catch it, write it to log/notify the user and exit the program, since the exceptions in these casese are generaly fatal, unrecoverable errors.

something like:

global_catch()
{
    MessageBox(NULL,L"Fatal Error", L"A fatal error has occured. Sorry for any inconvience", MB_ICONERROR);
    exit(-1);
}
global_catch(Exception *except)
{
    MessageBox(NULL,L"Fatal Error", except->ToString(), MB_ICONERROR);
    exit(-1);
}
+6  A: 

This can be used to catch, unexpected exceptions.

catch (...)
{
    cout << "OMG! an unexpected exception has been caught" << endl;
}

Without a try catch block, I don't think you can catch exceptions, so structure your program, so the exception thowing code is under the control of a try/catch.

EvilTeach
The thing is I really dont want to put my entire app in one big "super-try" block...since performance is kinda critical...I know theres some way somewhere because for example visual studio can detect/catch/whatever such exceptiosn and offer to break and debug.
Fire Lancer
The super try block works. You pay the cost of setting it up once in the main. Once is not a performance issue.
EvilTeach
just once? I'm sure once inside a try block it maintained some sort of "trace" for cleaning up after a throw, making the cost based on the contents of the block?
Fire Lancer
performance is not an issue, only when an exception is actually thrown does the system have to think about what to do. Stack unwinding is something the app has to do anyway as objects go out of scope.Besides, try it - its so easy to put try/catch in main, see if there is a performance hit.
gbjbaanb
As the context is that he wants to report and abort, the one try catch block should work for him.
EvilTeach
Using exception has practically no cost in modern compiler, unless an exception is thrown. At which point it is just as expensive as using any other method for finding and reporting errors.
Martin York
@Fire Lancer: The cost is only incurred if you have an exception. At which point your execution speed is no longer critical as something has gone wrong.
Martin York
The global catch(...) in main still won't catch exceptions in ctors of globals. E.g. A global std::vector<int>(size_t(-1)) will deplete memory before main() is called.
MSalters
@msalters a technique to get around that is to make your globals pointers, and allocate them in the main instead.
EvilTeach
A: 

This is what I always do in main()

int main()
{
    try
    {
        // Do Wrok
    }
    catch(std::exception const& e)
    {
         Log(e.what());
         // If you are feeling mad (not in main) you could rethrow! 
    }
    catch(...)
    {
         Log("UNKNOWN EXCEPTION");
         // If you are feeling mad (not in main) you could rethrow! 
    }
}
Martin York
+6  A: 

You can use SetUnhandledExceptionFilter on Windows, which will catch all unhandled SEH exceptions.

Generally this will be sufficient for all your problems as IIRC all the C++ exceptions are implemented as SEH.

gbjbaanb
+1  A: 

Without any catch block, you won't catch any exceptions. You can have a catch(...) block in your main() (and its equivalent in each additional thread). In this catch block you can recover the exception details and you can do something about them, like logging and exit.

However, there are also downside about a general catch(...) block: the system finds that the exception has been handled by you, so it does not give any more help. On Unix/Linux, this help would constitute creating a CORE file, which you could load into the debugger and see the original location of the unexcepted exception. If you are handling it with catch(...) this information would be already lost.

On Windows, there are no CORE files, so I would suggest to have the catch(...) block. From that block, you would typically call a function to resurrect the actual exception:

std::string ResurrectException()
   try {
       throw;
   } catch (const std::exception& e) {
       return e.what();
   } catch (your_custom_exception_type& e) {
       return e.ToString();
   } catch(...) {
       return "Ünknown exception!";
   }
}


int main() {
   try {
       // your code here
   } catch(...) {
       std::string message = ResurrectException();
       std::cerr << "Fatal exception: " << message << "\n";
   }
}
paavo256
Windows has .dmp files, which are roughly equivalent to core files, but they get uploaded to the Windows Error Reporting website (if the user clicks "send") instead of littering the user's hard drive. Also, if you have a just-in-time debugger configured, Windows will break into the debugger instead.
bk1e
+2  A: 

From More Effective C++ by Meyers (pg 76), you could define a function that gets called when a function generates an exception that is not defined by its exception specification.

void convertUnexpected()
{
    // You could redefine the exception here into a known exception
    // throw UnexpectedException();

    // ... or I suppose you could log an error and exit.
}

In your application register the function:

std::set_unexpected( convertUnexpected );

Your function convertUnexpected() will get called if a function generates an exception that is not defined by its exception specification... which means this only works if you are using exception specifications. ;(

ceretullis
A: 

Use catch (...) in all of your exception barriers (not just the main thread). I suggest that you always rethrow (...) and redirect standard output/error to the log file, as you can't do meaningful RTTI on (...). OTOH, compiler like GCC will output a fairly detailed description about the unhandled exception: the type, the value of what() etc.

ididak