2011-03-12 74 views
4

我有一個非常簡單的問題。如果一個C++程序員可以指導我,我會非常感激。我想在C++ dll中編寫C#代碼。你能指導嗎?如何從捕獲的異常中打印消息?

C#代碼翻譯:

void someMethod{ 
    try 
    { 
    //performs work, that can throw an exception 
    } 
    catch(Exception ex) 
    { 
     Log(ex.Message);//logs the message to a text file 
    } 
} 

//can leave this part, i can implement it in C++ 
public void Log(string message) 
{ 
//logs message in a file... 
} 

我已經做了在C++類似的東西,但我不能嘗試{}趕上(...)的消息部分。

+2

什麼類型的對象是你扔?它是一個'std :: exception'嗎? – Jon 2011-03-12 12:52:41

+1

消息是'std :: exception :: what()'。 http://www.cplusplus.com/reference/std/exception/exception/ – 2011-03-12 12:58:46

回答

1

嘗試:

#include <exception.h> 
#include <iostream> 
void someMethod() { 
    //performs work 
    try { 

    } 
    catch(std::exception ex) { 
     std::cout << ex.what() << std::endl; 
    } 
} 
+0

這可能會導致更復雜的例外。因爲你沒有通過引用趕上你正在啓動異常的複製構建到'ex'中。如果異常是從std :: exception(可能總是爲true)派生出來的,那麼在複製過程中會劃分異常(天氣這個實際問題將取決於實際異常)。結果總是被引用引用並且更喜歡const引用。 – 2011-03-12 13:10:49

+0

本來應該有一個'&',我無法打字。另外,除非需要修改異常,否則它應該是'const'。此外,應該添加「catch(...)'(應用程序的這裏或某處)以防止未處理的異常。 – steveo225 2011-03-12 13:18:12

+0

輸入錯誤有一個簡單的補救措施:編輯您的答案。 SO的答案對於不被誤解​​或誤導是很重要的。 – 2011-03-12 13:25:11

2
void someMethod{ 
//performs work 
try 
{} 
catch(std::exception& ex) 
{ 
    //Log(ex.Message);//logs the message to a text file 
    cout << ex.what(); 
} 
catch(...) 
{ 
    // Catch all uncaught exceptions 
} 

But use exceptions with care Exceptions in C++

+0

+1中糾正了gotw的鏈接。那篇文章有點舊了,現代圖書館已經適應了正常使用例外的條件,但它們仍然非常棘手。 – 2011-03-12 13:42:36

+0

如果**函數由DLL導出**,則捕獲所有內容是正確的。 – Wolf 2014-02-20 09:39:34

+0

執行工作評論在問題 – Wolf 2014-02-20 09:44:36

1

的原因,你不能獲得與例外:

try 
{ 
} 
catch (...) 
{ 
} 

是因爲你還沒有宣佈在catch塊中的異常變量。這將是(在C#)等價的:

try 
{ 
} 
catch 
{ 
    Log(ex.Message); // ex isn't declared 
} 

你可以得到異常與下面的代碼:

try 
{ 
} 
catch (std::exception& ex) 
{ 
} 
+0

中得到糾正嘗試「catch(...)」不是問題的一部分。我對嗎? – Wolf 2014-02-20 09:42:23

2

你可以大概想趕上拋出的所有異常。
所以加包羅萬象的(趕上(...))也爲:

try 
{ 
    // ... 
} 
catch(const std::exception& ex) 
{ 
    std::cout << ex.what() << std::endl; 
} 
catch(...) 
{ 
    std::cout << "You have got an exception," 
       "better find out its type and add appropriate handler" 
       "like for std::exception above to get the error message!" << std::endl; 
} 
+3

+1:但更喜歡通過const引用來捕獲異常。 – 2011-03-12 13:08:24

+0

@Martin +1,好抓,固定;) – 2011-03-12 13:10:42

0

我假設請求功能由DLL導出,所以防止任何飛行異常。

#include <exception.h> 

// some function exported by the DLL 
void someFunction() 
{ 
    try { 
     // perform the dangerous stuff 
    } catch (const std::exception& ex) { 
     logException(ex.what()); 
    } catch (...) { 
     // Important don't return an exception to the caller, it may crash 
     logException("unexpected exception caught"); 
    } 
} 

/// log the exception message 
public void logException(const char* const msg) 
{ 
    // write message in a file... 
} 
相關問題