How to print message from caught exception?

2019-02-23 18:13发布

I have a very simple question. Would really appreciate if a C++ programmer can guide me. I want to write the C# code below in C++ dll. Can you please guide?

C# code to be translated:

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... 
}

I have already done something similar in C++ but I can't get the message part of try{}catch(...).

5条回答
霸刀☆藐视天下
2楼-- · 2019-02-23 18:48

You may probably want to catch all the exceptions thrown.
So add catch all (catch(…)) also for that:

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楼-- · 2019-02-23 18:55

The reason you can't get the exception with:

try
{
}
catch (...)
{
}

is because you aren't declaring the exception variable in the catch block. That would be the equivalent of (in C#):

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

You can get the exception with the following code:

try
{
}
catch (std::exception& ex)
{
}
查看更多
Summer. ? 凉城
4楼-- · 2019-02-23 18:57

Try:

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

    }
    catch(std::exception ex) {
        std::cout << ex.what() << std::endl;
    }
}
查看更多
We Are One
5楼-- · 2019-02-23 19:09
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++

查看更多
别忘想泡老子
6楼-- · 2019-02-23 19:10

I assume that the requested function is exported by the DLL, so I prevent any flying exception.

#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... 
}
查看更多
登录 后发表回答