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

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.

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.

Catching Listener Exceptions in long running Cloud PubSub Subscriber service

I am trying to write a long running Subscriber service in Java. I have set up the Listeners to listen to any failures inside the Subscriber service. I am trying to make this fault tolerant and I do not quite understand few things, Below are my doubts/questions.
I have followed the basic setup shown here https://github.com/googleapis/google-cloud-java/blob/master/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java. Specifically, I have setup addListener as shown below.
As shown in the following code, initializeSubscriber acts a state variable which will determine if the Subscriber service should restart. Inside the while loop, this variable is continuously monitored to determine if the restart is required.
My question here is,
1. How do I raise an exception inside Subscriber.Listener's failed method and capture it in the main while loop. I tried throwing a new Exception() in failed method and catching it in catch block inside while, However, I am unable to compile the code as it is a checked exception.
2. As shown here, I use Java Executor thread to run the Listener. How do I handle the Listener failures ? Will I able to catch Listener failures under general Exception catch block as shown here ?
try {
boolean initializeSubscriber = true;
while (true) {
try {
if (initializeSubscriber) {
createSingleThreadedSubscriber();
addErrorListenerToSubscriber();
subscriber.startAsync().awaitRunning();
initializeSubscriber = false;
}
// Checks the status of subscriber service every minute
Thread.sleep(60000);
} catch (Exception ex) {
LOGGER.error("Could not start the Subscriber service", ex);
cleanupSubscriber();
initializeSubscriber = true;
}
}
} catch (RuntimeException e) {
} finally {
shutdown();
}
private void addErrorListenerToSubscriber() {
subscriber.addListener(
new Subscriber.Listener() {
#Override
public void failed(Subscriber.State from, Throwable failure) throws RuntimeException {
LOGGER.info("Subscriber reached a failed state due to " + failure.getMessage()
+ ",Restarting Subscriber service");
initializeSubscriber = true;
}
},
Executors.newSingleThreadExecutor());
}
private void cleanupSubscriber() {
try {
if (subscriber != null) {
subscriber.stopAsync().awaitTerminated();
}
if (!subscriptionListener.isShutdown()) {
subscriptionListener.shutdown();
}
} catch (Exception ex) {
LOGGER.error("Error in cleaning up Subscriber thread " + ex);
}
}
It should not be necessary to add a listener to the subscriber if you just want to recreate the subscriber on a failure. You could instead catch the exception on awaitTerminated:
try {
boolean initializeSubscriber = true;
while (initializeSubscriber) {
try {
createSingleThreadedSubscriber();
subscriber.startAsync().awaitRunning();
initializeSubscriber = false;
subscriber.awaitTerminated();
} catch (Exception ex) {
LOGGER.error("Error in the Subscriber service", ex);
cleanupSubscriber();
initializeSubscriber = true;
}
}
} catch (RuntimeException e) {
} finally {
shutdown();
}
If the subscriber shutdown successfully because of a call to stopAsync, then awaitTerminated will not throw an exception. If there was some kind of exception, then awaitTerminated will throw an IllegalStateException because the state will be FAILED instead of TERMINATED.
Note that transient errors are handled by the library itself. For example, if the server become briefly unavailable due to a network hiccup, the library will seamlessly reconnect and continue to deliver messages. Failures that result in a change in state for the subscriber are likely permanent failures such as permission issues (where the account running the subscriber does not have permission to subscribe to the subscription) or resource issues (such as the subscription having been deleted). In these permanent failure cases, recreating the subscriber will likely just result in the same error unless one takes manual steps to intervene and fix the problem.

Proper way to catch boost thread interrupt and exit thread

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

How to trace resource deadlocks?

I've wrote a timer using std::thread - here is how it looks like:
TestbedTimer::TestbedTimer(char type, void* contextObject) :
Timer(type, contextObject) {
this->active = false;
}
TestbedTimer::~TestbedTimer(){
if (this->active) {
this->active = false;
if(this->timer->joinable()){
try {
this->timer->join();
} catch (const std::system_error& e) {
std::cout << "Caught system_error with code " << e.code() <<
" meaning " << e.what() << '\n';
}
}
if(timer != nullptr) {
delete timer;
}
}
}
void TestbedTimer::run(unsigned long timeoutInMicroSeconds){
this->active = true;
timer = new std::thread(&TestbedTimer::sleep, this, timeoutInMicroSeconds);
}
void TestbedTimer::sleep(unsigned long timeoutInMicroSeconds){
unsigned long interval = 500000;
if(timeoutInMicroSeconds < interval){
interval = timeoutInMicroSeconds;
}
while((timeoutInMicroSeconds > 0) && (active == true)){
if (active) {
timeoutInMicroSeconds -= interval;
/// set the sleep time
std::chrono::microseconds duration(interval);
/// set thread to sleep
std::this_thread::sleep_for(duration);
}
}
if (active) {
this->notifyAllListeners();
}
}
void TestbedTimer::interrupt(){
this->active = false;
}
I'm not really happy with that kind of implementation since I let the timer sleep for a short interval and check if the active flag has changed (but I don't know a better solution since you can't interrupt a sleep_for call). However, my program core dumps with the following message:
thread is joinable
Caught system_error with code generic:35 meaning Resource deadlock avoided
thread has rejoined main scope
terminate called without an active exception
Aborted (core dumped)
I've looked up this error and as seems that I have a thread which waits for another thread (the reason for the resource deadlock). However, I want to find out where exactly this happens. I'm using a C library (which uses pthreads) in my C++ code which provides among other features an option to run as a daemon and I'm afraid that this interfers with my std::thread code. What's the best way to debug this?
I've tried to use helgrind, but this hasn't helped very much (it doesn't find any error).
TIA
** EDIT: The code above is actually not exemplary code, but I code I've written for a routing daemon. The routing algorithm is a reactive meaning it starts a route discovery only if it has no routes to a desired destination and does not try to build up a routing table for every host in its network. Every time a route discovery is triggered a timer is started. If the timer expires the daemon is notified and the packet is dropped. Basically, it looks like that:
void Client::startNewRouteDiscovery(Packet* packet) {
AddressPtr destination = packet->getDestination();
...
startRouteDiscoveryTimer(packet);
...
}
void Client::startRouteDiscoveryTimer(const Packet* packet) {
RouteDiscoveryInfo* discoveryInfo = new RouteDiscoveryInfo(packet);
/// create a new timer of a certain type
Timer* timer = getNewTimer(TimerType::ROUTE_DISCOVERY_TIMER, discoveryInfo);
/// pass that class as callback object which is notified if the timer expires (class implements a interface for that)
timer->addTimeoutListener(this);
/// start the timer
timer->run(routeDiscoveryTimeoutInMilliSeconds * 1000);
AddressPtr destination = packet->getDestination();
runningRouteDiscoveries[destination] = timer;
}
If the timer has expired the following method is called.
void Client::timerHasExpired(Timer* responsibleTimer) {
char timerType = responsibleTimer->getType();
switch (timerType) {
...
case TimerType::ROUTE_DISCOVERY_TIMER:
handleExpiredRouteDiscoveryTimer(responsibleTimer);
return;
....
default:
// if this happens its a bug in our code
logError("Could not identify expired timer");
delete responsibleTimer;
}
}
I hope that helps to get a better understanding of what I'm doing. However, I did not to intend to bloat the question with that additional code.

Unhandled exception when reading from disconected socket

I already do know, that it is impossible to simply detect if socket is disconnected or not - the server and clients must shout "Can you hear me?" and "Yeah I can." just like we do on skype.
But when boost::asio socket is disconnected from other side I obtain Unhanded exception when trying to read from socket. This is kind of disconnect detection useful enough for me. Can I handle that exception, so instead of crashing, the program will produce message in the console?
Some code for those who need it for everything:
bool SocketClient::read(int bytes, char *text) {
char buffer = 0;
int length = 0;
while(bytes>0) {
size_t len = sock.receive(boost::asio::buffer(&buffer, 1)); //boom: UNHANDLED EXCEPTION
bytes--;
text[length] = buffer;
length++;
}
return true;
}
Because I am connecting to minecraft server, I know when the client is disconnected - exception is caused on any read/write attempt.
try
{
size_t len = sock.receive(boost::asio::buffer(&buffer, 1)); //boom: UNHANDLED EXCEPTION
// More code ...
}
catch (const boost::system::system_error& ex)
{
if ( ex.code() == boost::asio::error::eof )
{
// Work your magic (console logging, retry , bailout etc.)
}
}
Please also take a look at the doc. In the worst case , you could infer the exception type from the debugger :)