2010-06-28 53 views
18

如果我想在每次捕獲全部異常時向文件寫入有用的信息,該怎麼做?如何獲取全部異常的消息

try 
{ 
    //call dll from other company 
} 
catch(...) 
{ 
    //how to write info to file here??????? 
} 
+2

什麼樣的消息,你想擺脫例外?如果拋出的對象是「int」呢?當你捕獲(...)時,你不知道捕獲到的異常將會有*消息。 – jalf 2010-06-28 14:09:51

+0

這個問題給了我一個奇怪的想法(它不會工作,但它會是一個有趣的事情,如果它):template catch(const T&ex){...}我不認爲它可能工作,因爲異常更多的是運行時機制......或者可以嗎?涉及拋出異常和分支到正確的catch塊的堆棧展開機制對我來說看起來很神奇。也許正確的catch分支仍然是在編譯時確定的,這將解釋爲什麼它跨越模塊邊界如此不安全的原因之一。 – stinky472 2010-06-29 08:27:14

回答

43

您無法從... catch塊獲取任何信息。這就是爲什麼代碼通常處理這樣的例外:

try 
{ 
    // do stuff that may throw or fail 
} 
catch(const std::runtime_error& re) 
{ 
    // speciffic handling for runtime_error 
    std::cerr << "Runtime error: " << re.what() << std::endl; 
} 
catch(const std::exception& ex) 
{ 
    // speciffic handling for all exceptions extending std::exception, except 
    // std::runtime_error which is handled explicitly 
    std::cerr << "Error occurred: " << ex.what() << std::endl; 
} 
catch(...) 
{ 
    // catch any other errors (that we have no information about) 
    std::cerr << "Unknown failure occurred. Possible memory corruption" << std::endl; 
} 
6

在catch-all處理程序中無法知道有關特定異常的任何信息。如果可以的話,最好能捕獲基類異常,比如std :: exception。

1

我認爲他想使它記錄發生的錯誤,但並不特別需要確切的錯誤(他會寫在這種情況下,他自己的錯誤文本)。

上面發佈的鏈接DumbCoder在教程中會幫助您獲得您想要實現的內容。

3

你不能得到任何細節。 catch(...)的整點是要有這樣的「我不知道會發生什麼,所以趕上拋出的東西」。對於已知的異常類型,您通常在catch之後放置catch(...)

8

捕獲到的異常可以通過函數std :: current_exception()來訪問,該函數在<例外>中定義。這是在C++ 11中引入的。

std::exception_ptr current_exception(); 

但是,性病:: exception_ptr是實現定義的類型,所以你不能去的細節呢。 typeid(current_exception()).name()告訴你exception_ptr,而不是包含的異常。所以你可以用它做的唯一事情是std :: rethrow_exception()。 (這個功能似乎是在那裏來標準化跨線程的傳遞和重新拋出。)