2010-06-19 41 views
27

我有一些程序,每次運行它時,它會拋出異常,我不知道如何檢查它究竟拋出了什麼,所以我的問題是,是否有可能捕獲異常打印(我發現它拋出異常行)在此先感謝如何捕獲未知的異常並打印它

回答

32

如果從std::exception派生您可以參考趕上:

try 
{ 
    // code that could cause exception 
} 
catch (const std::exception &exc) 
{ 
    // catch anything thrown within try block that derives from std::exception 
    std::cerr << exc.what(); 
} 

但是,如果該異常是一些類已經不是從std::exception衍生,你將必須提前知道它的類型(即你應該趕上std::stringsome_library_exception_base)。

你可以做一個包羅萬象的:

try 
{ 
} 
catch (...) 
{ 
} 

但你不能做的事情除外。

+0

@R Samuel Klatchko:非常感謝,還有一個問題,我可以用你的方法檢查新的和刪除的異常嗎? – helloWorld 2010-06-19 07:17:17

+0

@helloWorld - 是的,這將捕獲'new','delete'以及由它們調用的任何構造函數或析構函數拋出的異常(只要'new'或'delete'語句在'try'塊內)。 – 2010-06-19 15:58:26

+3

如果異常不是從std :: exception派生的,我應該如何解決我的問題? – javapowered 2014-04-22 15:26:35

1

請按照R Samuel Klatchko的建議嘗試。如果這沒有幫助,還有其他可能的幫助:

a)如果調試器支持,則在異常類型(已處理或未處理)上放置斷點。

b)在某些系統上,當執行throw語句時,編譯器會生成對(未記錄的?)函數的調用。找出你係統的功能是什麼,編寫一個簡單的Hello World程序,拋出並捕獲一個異常。啓動一個調試器並在異常構造函數中放置一個斷點,並從中調用它。 caling函數可能類似於__throw()。之後,再用你想作爲調試對象的程序啓動調試器。在上述函數(__throw或其他)上放置斷點並運行程序。當拋出異常時,調試器會停止,並且您正在那裏找出原因。

11

在C++ 11你有:從現場std::current_exception

示例代碼:

#include <iostream> 
#include <string> 
#include <exception> 
#include <stdexcept> 

void handle_eptr(std::exception_ptr eptr) // passing by value is ok 
{ 
    try { 
     if (eptr) { 
      std::rethrow_exception(eptr); 
     } 
    } catch(const std::exception& e) { 
     std::cout << "Caught exception \"" << e.what() << "\"\n"; 
    } 
} 

int main() 
{ 
    std::exception_ptr eptr; 
    try { 
     std::string().at(1); // this generates an std::out_of_range 
    } catch(...) { 
     eptr = std::current_exception(); // capture 
    } 
    handle_eptr(eptr); 
} // destructor for std::out_of_range called here, when the eptr is destructed 
0

人Dawid德羅茲德答案啓發:

包含這個頭#include <exception>

try 
{ 
    // The code that could throw 
} 
catch(...) 
{ 
    auto expPtr = std::current_exception(); 

    try 
    { 
     if(expPtr) std::rethrow_exception(expPtr); 
    } 
    catch(const std::exception& e) //it would not work if you pass by value 
    { 
     std::cout << e.what(); 
    } 
}