English 中文(简体)
using catch(...) (ellipsis) for post-mortem analysis
原标题:

Someone in a different question suggested using catch(...) to capture all otherwise unhandled - unexpected/unforseen exceptions by surrounding the whole main() with the try{}catch(...){} block.

It sounds like an interesting idea that could save a lot of time debugging the program and leave at least a hint of what happened.

The essence of the question is what information can be recovered that way (other than whatever debug globals I leave behind), and how to recover it (how to access and recognize whatever catch was called with)

Also, what caveats are connected with it. In particular:

  • will it play nice with threads that sprout later?
  • will it not break handling segfaults (captured elsewhere as signal)
  • will it not affect other try...catch blocks inevitably nested inside, that are there to handle expected exceptions?
最佳回答

Yes it is a good idea.

If you let an exception escape main it is implementation defined weather the stack is unwound before the application is shut down. So in my opinion it is essential you catch all exceptions in main.

The question then becomes what to do with them.
Some OS (See MS and SE) provide some extra debugging facilities so it is useful to just re-throw the exception after you catch it (because the stack has been unwound now anyway).

int main()
{
    try
    {
        /// All real code
    }
    // I see little point in catching other exceptions at this point 
    // (apart from better logging maybe). If the exception could have been caught
    // and fixed you should have done it before here.

    catch(std::exception const& e)
    {
         // Log e.what() Slightly better error message than ...
         throw;
    }
    catch(...)   // Catch all exceptions. Force the stack to unwind correctly.
    {
        // You may want to log something it seems polite.
        throw;  // Re-throw the exception so OS gives you a debug opportunity.
    }
}
  • will it play nice with threads that sprout later?

It should have no affect on threads. Usually you have to manually join any child threads to make sure that they have exited. The exact details of what happens to child threads when main exits is not well defined (so read your documentation) but usually all child threads will die instantly (a nasty and horrible death that does not involve unwinding their stacks).

If you are talking about exceptions in child threads. Again this is not well defined (so read your documentation) but if a thread exits via an exception (ie the function used to start the thread exits because of an exception and not a return) then this usually causes the application to terminate (same affect as above). So it is always best to stop ALL exceptions from exiting a thread.

  • will it not break handling segfaults (captured elsewhere as signal)

Signals are not affected by the exception handling mechanism.
But because signal handlers may place an odd structure on the stack (for their own return handling back to normal code) it is not a good idea to throw an exception from within a signal handler as this may cause unexpected results (and is definitely not portable).

  • will it not affect other try...catch blocks inevitably nested inside, that are there to handle expected exceptions?

Should have no effect on other handlers.

问题回答

As far as I remember, catch(...) on Win32 catches also SEH exceptions, and you do not want to do that. If you get a SEH exception it s because something very scary happened (mainly access violations), so you can t trust your environment anymore. Almost everything you could do may fail with another SEH exception, so it s not even worth trying. Moreover, some SEH exceptions are intended to be caught by the system; more on this here.

So, my advice is to use a base exception class (e.g. std::exception) for all your exceptions, and catch just that type in the "catchall"; your code cannot be prepared to deal with other kind of exceptions, since they are unknown by definition.

A global try catch block is useful for production systems, in order to avoid displaying a nasty message to the user. During development I believe that are best avoided.

Regarding your questions:

  • I believe that a global catch block won t catch exceptions in another thread. Each thread has its own stack space.
  • I am not sure about this.
  • Nested try...catch blocks aren t affected and will execute as usual. An exception propagates up the stack, until it finds a try block.

You could try a solution I use if you re making a .net application. That captures all unhandled exceptions. I generally only enable the code (with #ifndef DEBUG) for production code when I m not using the debugger.

It s worth pointing out as kgiannakakis mentions that you can t capture exceptions in other threads, but you can use the same try-catch scheme in those threads and post the exceptions back to the main thread where you can re-throw them to get a full stack track of what went wrong.

and how to recover it (how to access and recognize whatever catch was called with)

If you mean how to recover the type of exception that was thrown, you can chain catch blocks for specific types (proceeding from more specific to more general) before falling back to catch (...):

try {
   ...
} catch (const SomeCustomException& e) {
   ...
} catch (const std::bad_alloc& e) {
   ...
} catch (const std::runtime_error& e) {
   // Show some diagnosic for generic runtime errors...
} catch (const std::exception& e) {
   // Show some diagnosic for any other unhandled std::exceptions...
} catch (...) {
   // Fallback for unknown errors.
   // Possibly rethrow or omit this if you think the OS can do something with it.
}

Note that if you find yourself doing this in multiple places and want to consolidate code (maybe multiple main functions for separate programs), you can write a function:

void MyExceptionHandler() {
   try {
      throw; // Rethrow the last exception.
   } catch (const SomeCustomException& e) {
      ...
   }
   ...
}

int main(int argc, char** argv) {
   try {
      ...
   } catch (...) {
      MyExceptionHandler();
   }
}

A catch-all will not be terribly useful since there is no type/object information that you can query. However, if you can make sure all exceptions raised by your application are derived from a single base object, you can use a catch block for the base exception. But then that wouldn t be a catch-all.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签