我有一个非常简单的问题。如果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 ++中做了类似的事情,但是我无法将消息作为try {} catch(...)的一部分。
答案 0 :(得分: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
}
答案 1 :(得分:2)
您可能想要捕获所有抛出的异常 所以为此添加catch all(catch(...)):
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;
}
答案 2 :(得分:1)
尝试:
#include <exception.h>
#include <iostream>
void someMethod() {
//performs work
try {
}
catch(std::exception ex) {
std::cout << ex.what() << std::endl;
}
}
答案 3 :(得分:1)
您无法通过以下方式获取例外的原因:
try
{
}
catch (...)
{
}
是因为您没有在catch块中声明异常变量。这相当于(在C#中):
try
{
}
catch
{
Log(ex.Message); // ex isn't declared
}
您可以使用以下代码获取异常:
try
{
}
catch (std::exception& ex)
{
}
答案 4 :(得分: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...
}