How to print message from caught exception?

12,000

Solution 1

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

Solution 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++

Solution 3

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)
{
}

Solution 4

Try:

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

    }
    catch(std::exception ex) {
        std::cout << ex.what() << std::endl;
    }
}
Share:
12,000
InfoLearner
Author by

InfoLearner

Updated on June 05, 2022

Comments

  • InfoLearner
    InfoLearner almost 2 years

    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(...).