代码之家  ›  专栏  ›  技术社区  ›  Yippie-Ki-Yay

C++未处理异常

  •  7
  • Yippie-Ki-Yay  · 技术社区  · 16 年前

    我想做的是 assert(unhandled exception.msg())

    void foo() {
       throw std::exception("Message!");
    }
    
    int main() {
     foo();
    }
    

    我希望这种代码不会立即终止(因为异常未处理),而是显示自定义断言消息( Message! 实际上)。

    有可能吗?

    8 回复  |  直到 16 年前
        1
  •  13
  •   Logan Capaldo    16 年前

       void terminate_handler()
       {
           try { throw; }
           catch(const std::exception& e) { log(e.what()); }
           catch(...) {}
       }
    

    简而言之,没有通用的C++方式,但是有很多方法取决于你的平台。

        2
  •  6
  •   Steve Townsend    16 年前

    微软Visual C++允许你钩住未处理的C++异常 like this . 这是 standard STL behaviour

    通过调用 set_terminate

        3
  •  4
  •   Community Mohan Dere    9 年前

    如果您使用的是Windows,那么可以使用一个很好的库来处理未处理的异常和崩溃 CrashRpt use the following I wrote in this answer .

        4
  •  4
  •   Christopher Hunt    16 年前

    int main() {
     try {
       foo();
     catch (...) {
       // Do something with the unhandled exception.
     }
    }
    
        5
  •  2
  •   karlphillip    16 年前

    是的,有可能。干得好:

    #include <iostream>
    #include <exception>
    
    void foo() 
    {
       throw std::exception("Message!");
    }
    
    int main() 
    {
      try
      {
        foo();
      }
      catch (std::exception& e)
      {
        std::cout << "Got exception: " << e.what() << std::endl;
      }
    
      return 0;
    }
    
        6
  •  1
  •   David Titarenco    16 年前

    throw (更改其默认行为)以便它执行用户定义的操作。不,你不能。

    编辑:既然你坚持:),这里有一个 坏主意 :

    #include <iostream>
    #include <stdlib.h>
    #include <windows.h>
    
    void monkey() {
       throw std::exception("poop!");
    }
    
    LONG WINAPI MyUnhandledExceptionFilter(struct _EXCEPTION_POINTERS *lpTopLevelExceptionFilter) {
        std::cout << "poop was thrown!" << std::endl;
        return EXCEPTION_EXECUTE_HANDLER;
      }
    
    int main() {
        SetUnhandledExceptionFilter(&MyUnhandledExceptionFilter);
        monkey();
        return 1;
    }
    

    同样,这是一个非常糟糕的想法,它显然依赖于平台,但它是有效的。

        7
  •  0
  •   pm100    16 年前

    c++标准是终止处理程序——正如其他标准所说

    我们有一个宏抛出,记录文件名、行号和消息,然后抛出。它接受printf样式的varargs消息。

    Throw(proj::FooException, "Fingle %s unable to process bar %d", fingle.c_str(), barNo);
    

    我收到一条很好的日志消息

    Throw FooException from nargle.cpp:42 Fingle barf is unable to process bar 99
    
        8
  •  0
  •   SingleNegationElimination    16 年前

    如果您真的对导致程序失败的原因感兴趣,那么可以在事后调试程序中检查进程映像。精确的技术因操作系统而异,但基本的方法是首先启用内核转储,然后用调试符号编译程序。一旦程序崩溃,操作系统会将其内存复制到磁盘,然后您可以检查程序崩溃时的状态。

    推荐文章