Reputation: 15608
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(...).
Upvotes: 4
Views: 12723
Reputation: 10236
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...
}
Upvotes: 0
Reputation: 1151
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;
}
Upvotes: 2
Reputation: 20332
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)
{
}
Upvotes: 1
Reputation: 5766
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++
Upvotes: 2
Reputation: 11892
Try:
#include <exception.h>
#include <iostream>
void someMethod() {
//performs work
try {
}
catch(std::exception ex) {
std::cout << ex.what() << std::endl;
}
}
Upvotes: 1