How to print a message from a caught exception?

I have a very simple question. It would be very helpful if a C ++ programmer can guide me. I want to write C # code below in a C ++ dll. Could you advise?

C # code for translation:

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 already did something similar in C ++, but I can’t get the part of the try {} catch (...) message.

+4
source share
5 answers
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 caution . Exceptions in C ++

+2
source

You might want to catch all the exceptions that have been thrown.
So add catch all (catch (...)) also for this:

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
source

Try:

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

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

, :

try
{
}
catch (...)
{
}

, catch. ( #):

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

:

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

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

#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... 
}
0
source

All Articles