Proper way to catch boost thread interrupt and exit thread - c++

I have the code below which is the start of a new thread. BeginWork function goes through a sequence of functions that have heavy exception handling. If threadgroup.interrupt_all(); is called the individual function will handle the interrupt and this causes the thread to remain in it's loop without being interrupted properly. How can I change my error handling to account for this type of exception and mimic the behavior as if the outer try catch block of the intial loop caught the thread interrupt exception? I'm thinking maybe catch the exception of time interupt and set a boolean to true which is checked within the main loop and break if it is set to true.
void ThreadWorker(int intThread)
{
try
{
int X = 0;
do
{
cout << "Thread " << intThread << "\n";
BeginWork();
}
while (true);
}
catch(...)
{
cout << "Thread: " << intThread << " Interrupted.";
}
}

You can easily do it by boost::thread_interrupted rethrowing in a function catch site
try
{
// data processing
}
catch(const boost::thread_interrupted &)
{
throw;
}
catch(...)
{
// exceptions suppression
}
But i think it's not a very good idea to handle all exceptions inside every function. Better way is to handle only specific exceptions, allowing others to propagate further to the top level function, where they will be handled.
Maybe this site will be useful for you

Related

How to stop catching signal(Ctrl + c) exception in debug mode

I'm implementing std::signal into my server application to shut it down safely.
void signal_handler(int signal)
{
if (signal == SIGINT)
{
std::cout << "Hello.\n";
exit(signal);
}
}
void threadFunc()
{
while (gLoop)
{
std::cout << "Hello..\n";
std::this_thread::sleep_for(1s);
}
}
int main()
{
std::signal(SIGINT, signal_handler);
std::thread thrd{ threadFunc };
thrd.join();
}
This is an example code
It works fine when I run it as release mode..
But it stops when I press Ctrl+c in debug mode and of course notify me that exception occurred.
I just want it to ignore the exception and see what I've done something wrong in the terminating process (memory leaks, violation exception etc.)
Is there anyway that I can do for it?
I figured it out just a second after I post this!
I can do it by just disabling catch this exception next time setting in the exception box.

Is it bad to throw an exception and ignore "reaches end of non-void function" warnings?

My code:
QSerialPortInfo getCentralInfo()
{
const QList<QSerialPortInfo> infoList =
QSerialPortInfo::availablePorts();
for (auto it = infoList.cbegin();
it != infoList.cend(); ++it) {
if (it->manufacturer() == "1a86") {
happyTalk("Znaleziono centralkę.");
return *it;
}
}
escape("Nie znaleziono centralki.");
}
void escape(QString errorMsg) {
qDebug() << "[!] " << errorMsg;
throw;
}
void happyTalk(QString msg) {
qDebug() << "[\u2713] " << msg;
}
Is it elegant to stop the application like that and why is it not? I'm getting debugger warnings but I think the debugger is wrong here. ;-)
Add the [[noreturn]] attribute to escape, and actually throw an object.
[[noreturn]] tells the compiler, optimizer and hopefully warning generator that escape never returns, so it should (in an ideal world) block that error.
The issue here is that
throw;
does not mean "throw some exception." It means "rethrow the exception currently being processed." If you execute throw with no active exception, I believe it calls std::terminate to end the program.
A more elegant way to handle this would either be to throw an exception (perhaps a std::logic_error) to indicate that something bad happened and transfer control to an error handler, or to exit the program by calling exit or abort.
Hope this helps!

exception while thread is throwing error in scoket c++ windows

i am creating client sever application in windows using socket and i want to throw exception at run time from thread if any problem occur but i am getting error for throw statement.
//create thread in cpp file
CreateThread(NULL,0,startServer,this,0,NULL);
//thread in header file
static unsigned long __stdcall startServer(void *i_SocketTransportServer)
{
((SocketTransportServer*)i_SocketTransportServer)->StartServerThread(((SocketTransportServer *)i_SocketTransportServer)->m_socketServer);
return 0;
}
//and StartServerThread is function called by thread
// SocketTransportServer is inner class of RMLThinTransport
void RMLThinTransport::SocketTransportServer::StartServerThread(SOCKET i_socketServer)
{
m_socketAccept=NULL;
while(true)
{
Sleep(20);
if(m_canAcceptMore)
{
m_canAcceptMore=false;
if(!m_isRunning)
{
break;
}
try
{
m_socketAccept=accept(m_socketServer,NULL,NULL);
if(m_socketAccept==INVALID_SOCKET)
{
int lastError=WSAGetLastError();
closesocket(m_socketAccept);
SocketExceptions
exceptionInAcceptAtServer;
exceptionInAcceptAtServer.detectErrorAccept(&lastError);
throw exceptionInAcceptAtServer;
}
else
{
//_LOG("Client connected",EventTypeInfo) ;
OutputDebugStringW(L"client connected.....");
/* If client connected then setClinetCout value 1 */
setClientCount(1);
m_ClientSockets.push_back(m_socketAccept);
CreateThread(NULL,0,receiveDataAtServer,this,0,NULL);
}
}
catch(SocketExceptions& i_exceptionInAcceptAtServer)
{
/*OutputDebugStringW(L"Can't accept client In Exception. ."); */
throw i_exceptionInAcceptAtServer;//getting runtime error from here
}
}
}
}
now i want to throw error when server close but i am getting run time error. so is there any way so i can get error in my main function.sorry but i am new in c++ so please help me. and error is
The code that throws the exception is not the problem; it's the lack of any code to catch the exception that's the problem. The application is terminating because nothing is catching the exception you're throwing; you must ensure that something is going to catch it. Your startServer method -- the thread procedure -- must catch the exception, and cleanly exit the thread.

c++ exceptions and program execution logic

I have been thru a few questions but did not find an answer.
I wonder how should the exception handling be implemented in a C++ software so it is centralized and it is tracking the software progress?
For example, I want to process exceptions at four stages of the program and know that exception happened at that specific stage:
1. Initialization
2. Script processing
3. Computation
4. Wrap-up.
At this point, I tried this:
int main (...)
{
...
// start logging system
try {
...
}
catch (exception &e)
{
cerr << "Error: " << e.what() << endl;
cerr << "Could not start the logging system. Application terminated!\n";
return -1;
}
catch(...)
{
cerr << "Unknown error occured.\n";
cerr << "Could not start the logging system. Application terminated!\n";
return -2;
}
// open script file and acquire data
try {
...
}
catch (exception &e)
{
cerr << "Error: " << e.what() << endl;
cerr << "Could not acquire input parameters. Application terminated!\n";
return -1;
}
catch(...)
{
cerr << "Unknown error occured.\n";
cerr << "Could not acquire input parameters. Application terminated!\n";
return -2;
}
// computation
try {
...
}
...
This is definitely not centralized and seems stupid.
Or maybe it is not a good concept at all?
You could keep a global variable containing the state of the program, and print it out in the catch block. Then you would only need two catch blocks, one for std::exception and one for everything else.
It seems to me that you're trying to use exceptions as (more or less) a replacement for logging. I think in this case, you'd be a lot better off using the two together -- in particular, I'd probably have a small exception handler that put output in the log, so your code would look something like this:
try {
// start logging system
}
catch (exception const &e) { std::cerr << e.what << "error starting logging"; }
catch (...) { std::cerr << "Unknown error starting logging"; }
try {
{ scoped_log("script processing");
start_script();
}
{ scoped_log("computation");
do_computation();
}
{ scoped_log("wrap up");
wrap_up();
}
}
catch(std::exception const &e) { log << "error: " << e.what() << "\n"; }
catch(...) { log << "Unknown exception\n"; }
where "scoped_log" is a simple class something like:
class scoped_log {
std::string caption;
public:
scoped_log(std::string const &c) : caption(c) {
log << "Starting: " << caption << "\n";
}
~scoped_log() { log << "Finished: " << caption << "\n"; }
};
This allows you to centralize most of the exception handling. The only exception (no pun intended) is for starting up the logging system itself -- you obviously can't use logging to report problems with starting up the logging system.
Once the logging system is up, however, things are a lot simpler -- you use the combination of logging and exception handling to track down when the problem occurred. Keep one minor detail in mind: since the scoped_log is an object that's destroyed when the scope is exited (for any reason), the log will have a structure that might (at least initially) seem a bit misleading -- the error message will follow the "finshed xxx" message in the log. For example, if a script file couldn't be opened, your log might look something like this:
starting script processing
finished script processing
error: could not open file: 'script.input'
At least IMO, that's unlikely to cause a problem if you're aware of the situation.
In my opinion, exceptions should be (generally) caught in 5 conditions:
You can legitimately handle the exception and continue normally (e.g. you caught a boost::bad_lexical_cast from user input, but can recover by reporting the error to the user).
You need to translate the exception from one source to another (e.g. your library uses another library as a pure implementation detail and wants to translate a 'socket_exception' into a 'service_exception' or something of the sort). In .Net, I'd do this by throwing a new exception instance w/ an inner exception. In C++, it can be useful to provide a consistent interface to your users, especially if you're, for instance, only throwing exceptions derived from std::exception, but a dependent library throws exceptions from a non-standard type (string, int, const char*, custom type, etc).
You're writing a cross language wrapper. C++/C, C++/Fortran, etc. C++ exceptions don't tend to cross these barriers well, and you're best off translating them into the target runtime's error handling facilities, if possible.
You're in main, and wish to capture some slight information from the exception & log before you crash. If you do so, there's two primary camps on what to do next: exit(1) or throw; and generate a core (on *nix). I've mixed feelings...
much like in main, around a thread entry. Can be helpful to log why a thread terminated, and then treat thread termination in a appropriate manner.
A simple way of having exception processing centralized is creating a simple function to process the exceptions and then using a generic catch that calls the function:
void processExceptions( std::string const & stage )
{
std::cout << "Exception caught at stage " << stage << std::endl;
try {
throw; // rethrow the last caught exception
}
catch ( exception1 const & ) {
// do process 1
}
catch ( exception2 const & ) {
// ...
}
}
int main()
{
try {
initialize();
}
catch ( ... ) {
processExceptions( "initialization" );
}
try {
stage2();
}
catch ( ... ) {
processExceptions( "stage2" );
}
}
I have never used that technique to identify when an exception was caught, but it is quite useful to avoid duplicating exception processing code in many places if it is the same.
Note that if you call the function when no exception has been thrown (outside of a catch) you will get undefined behavior and more often than not your application will die.
The other alternative is to have distinct, by-you-defined exceptions which you then handle in one central place instead of different return values. So when the exception occurs like "could not acquire input parameters" you would throw something like an "invalid_parameters exception" with some more context information added about the reason for the exception. Then in a central place you display the error.
If you really want to more centralize this, you could define your own error classes such as
class does_not_open {};
class cannot_write {};
or so. You'll need more work in your different parts, e.g., check if open succeeds; if not, throw does_not_open (etc.). But after you organize yourself this way, you can put the entire main part of your code into the following form:
try{
}
catch(does_not_open &e){
}
catch(cannot_write &e){
- your code here -
}
catch(...){
- your code here -
}
Not sure this accomplishes what you were hoping for...but gl. :)

How to log an c++ exception

Do you know how can I log the exception ?
right now the message in the catch statement is printed, but i cannot understood why ins´t Manage.Gere() called sussefully .
try{
Manager.Gere(&par,&Acc, coman, comando, RunComando, log, &parti, comandosS, RunComandosSuper,true);
}
catch (...)
{
log("ERROR ENTER GERE*****");
}
Perif::Gere(CString *par, CString *Acc, HANDLE coman, HANDLE comando, HANDLE RunComando, Log &log, CString *parti, HANDLE comandosS, HANDLE RunComandosSuper,bool first)
{
log->LogD("Perif :: Gere Enter****** "); //It doesnt get printed
}
A well-behaved API should only throw objects of types derived from std::exception. If that's the case, then the exception will have a member function const char *what() containing a message, which will hopefully describe the error. So you could try this, and hope that it helps:
try {
Manage.Gere(...);
} catch (const std::exception &e) {
log(e.what());
} catch (...) {
log("Manage.Gere threw unknown exception");
}
If it throws a type that isn't a std::exception, then you will need to look at the documentation and/or source for the function to see what could go wrong, and what types it does throw. If none of this is available, I would be looking for a better library.
First thing you need there is find which exceptions Manage.Gere can throw.
Then catch them specifically like catch(FirstExceptionGereThrows &exc) and when you catch all possible exceptions, you'll know what is failing in Manage.Gere.
catch(FirstException &exc){
log << "Failed because FirstException\n";
}catch(SecondException &exc){
log << "Failed because SecondException\n";
}
After, and if you are lucky enough the exceptions thrown by Manage.Gere may include some extra info about the crash which you could log as well.
catch(FirstException &exc){
log << "Failed because FirstException: " << exc.what() << "\n";
}
As others have suggested, RTFM is really the answer. However, I've found that lazy programmers often write code like:
if ( something ) {
throw "Something has happened!";
}
so it is always worthwhile trying to catch both const char * ans std::string:
try {
// stuff
}
catch( const char * s ) {
cerr << s << endl;
}
catch( const std::string & s ) {
cerr << s << endl;
}
// other catches here
You can also use my tool as an external debugger which catches C++ exceptions and automatically create minidump files for offline debugging. See http://alax.info/blog/1211 for details.
The good thing is that you don't need any code for this, or you can even debug an application which you don't have code for, or you cannot rebuild it for any reason. The dump file will get you stacks and information, and the application will be able to continue execution.